Cod sursa(job #2714759)

Utilizator marius004scarlat marius marius004 Data 2 martie 2021 14:39:41
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream f("apm.in");
ofstream g("apm.out");

vector < int > disjointSet;
vector < tuple < int, int, int > > edges;

int getRoot(int x) {

    int root = x;

    for(;disjointSet[root] > 0;root = disjointSet[root]);

    return root;
}

void unify(int x, int y) {

    int rootX = getRoot(x);
    int rootY = getRoot(y);

    if(-disjointSet[rootX] < -disjointSet[rootY])
        swap(rootX, rootY);

    disjointSet[rootX] += disjointSet[rootY];
    disjointSet[rootY]  = rootX;
}

bool sameRoot(int x, int y) {
    return getRoot(x) == getRoot(y);
}

int main() {

    int n, m;
    f >> n >> m;

    disjointSet.resize(n + 1, -1);

    for(;m--;) {
        int x, y, c;
        f >> x >> y >> c;
        edges.push_back(make_tuple(x, y, c));
    }

    sort(edges.begin(), edges.end(),[](const tuple<int, int, int>& a, const tuple<int, int, int>& b) -> bool {
        return get<2>(a) < get<2>(b);
    });

    int cnt{}, ind{}, cost{};
    vector < int > edges_used;

    for(auto& edge : edges) {

        int rootX = getRoot(get<0>(edge));
        int rootY = getRoot(get<1>(edge));

        if(rootX != rootY) {
            cost += get<2>(edge);
            cnt++;
            unify(rootX, rootY);
            edges_used.push_back(ind);
        }

        if(cnt == n - 1)
            break;

        ind++;
    }

    g << cost << '\n';

    for(auto& it : edges_used)
        g << get<0>(edges[it]) << ' ' << get<1>(edges[it]) << '\n';

    return 0;
}