Cod sursa(job #3192384)

Utilizator mihaistamatescuMihai Stamatescu mihaistamatescu Data 12 ianuarie 2024 14:53:44
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <tuple>
#include <vector>
#include <algorithm>

using namespace std;
int n, m;

int t[200010];
vector<tuple<int, int, int>> muchii;
vector<pair<int, int>> solMuchii;

int getRoot(int x) {
    int root = x;
    while (t[root] > 0) {
        root = t[root];
    }
    while (x != root) {
        int aux = t[x];
        t[x] = root;
        x = aux;
    }
    return root;
}

bool join(int x, int y) {
    int xRoot = getRoot(x);
    int yRoot = getRoot(y);
    if (xRoot == yRoot) {
        return false;
    }
    if (t[xRoot] <= t[yRoot]) {
        t[xRoot] += t[yRoot];
        t[yRoot] = xRoot;
    } else {
        t[yRoot] += t[xRoot];
        t[xRoot] = yRoot;
    }
    return true;
}

int main() {
    ifstream fin("apm.in");
    ofstream fout("apm.out");
    int x, y, c, solCost = 0;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        muchii.emplace_back(make_tuple(c, x, y));
    }
    sort(muchii.begin(), muchii.end());
    for (int i = 1; i <= n; i++) {
        t[i] = -1;
    }
    for (tuple<int, int, int> &a:muchii) {
        c = get<0>(a);
        x = get<1>(a);
        y = get<2>(a);
        if (join(x, y)) {
            solCost += c;
            solMuchii.emplace_back(make_pair(x, y));
        }
    }
    fout << solCost << "\n" << solMuchii.size() << "\n";
    for (auto &a:solMuchii) {
        fout << a.first << " " << a.second << "\n";
    }
    return 0;
}