Cod sursa(job #3252965)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 31 octombrie 2024 16:38:03
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>

using namespace std;

struct Edge {
    int x, y, cost;
};

bool cmp(Edge a, Edge b) {
    return a.cost < b.cost;
}

struct DSU {
    vector<int> p, h;
    DSU(int n) {
        p.resize(n + 1);
        h.resize(n + 1);
        for(int i = 1; i <= n; i++) {
            p[i] = i;
            h[i] = 1;
        }
    }
    int Find(int x) {
        int r = x;
        while(r != p[r]) {
            r = p[r];
        }
        //compresia drumurilor
        int y = x;
        while(y != r) {
            int t = p[y];
            p[y] = r;
            y = t;
        }
        return r;
    }
    void Union(int x, int y) {
        x = Find(x);
        y = Find(y);
        //reuniune dupa rang
        if(h[x] < h[y]) {
            p[x] = y;
        } else {
            if(h[x] > h[y]) {
                p[y] = x;
            } else {
                p[x] = y;
                h[y]++;
            }
        }
    }

};

int main() {
    ifstream f("apm.in");
    ofstream g("apm.out");
    int n, m;
    f >> n >> m;
    DSU d(n);
    vector<Edge> edges;
    for(int i = 1; i <= m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        edges.push_back({x, y, c});
    }
    sort(edges.begin(), edges.end(), cmp);
    int apm = 0;
    vector<Edge> v;
    for(auto it : edges) {
        if(d.Find(it.x) != d.Find(it.y)) {
            apm += it.cost;
            d.Union(it.x, it.y);
            v.push_back(it);
        }
    }
    g << apm << '\n';
    g << v.size() << '\n';
    for(auto it : v) {
        g << it.x << ' ' << it.y << '\n';
    }
    return 0;
}