Cod sursa(job #3320146)

Utilizator iuliarusuIulia Rusu iuliarusu Data 4 noiembrie 2025 13:01:06
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("apcm.in");
ofstream g("apcm.out");

struct muchie {
    int x, y, c;
};
int p[200001], h[200001];
muchie v[400001];
vector<pair<int,int>> a;
bool cmp(muchie a, muchie b) {
    return a.c < b.c;
}
int Find(int x) {
    while (x!=p[x]) {
        x = p[x];
    }
    return x;
}
void Union(int x, int y) {
    x = Find(x);
    y = Find(y);
    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() {
    int n, m;
    f >> n >> m;
    for (int i=1; i<=m; i++) {
        int x,y,c;
        f >> x >> y >> c;
        v[i] = {x,y,c};
    }
    for (int i=0; i<=n;i++) {
        p[i]=i;
        h[i] = 1;
    }
    sort(v+1, v+m+1, cmp);
    int sol = 0;
    for (int i=1; i<=m; i++) {
        if (Find(v[i].x) != Find(v[i].y)) {
            sol+=v[i].c;
            a.push_back({v[i].x, v[i].y});
            Union(v[i].x, v[i].y);
        }
    }
    g << sol << "\n";
    g << a.size() << "\n";
    for (auto& i : a) {
        g << i.first << " " << i.second << "\n";
    }
}