Cod sursa(job #3373110)

Utilizator MateoTdrTeodorescu Mateo MateoTdr Data 6 noiembrie 2026 09:01:08
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <algorithm>

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

struct muchie {
    int x, y, c;
};

const int NMAX = 2e5;
const int MMAX = 4e5;
int p[NMAX + 1]; //p[i] parintele nodului i
int sz[NMAX + 1]; //sz[i] numarul de noduri din arborele cu radacina in i
muchie v[MMAX + 1]; //vectorul de muchii
muchie sol[MMAX + 1]; 

int find(int x) { //radacinca arborelui in care se afla x
   while(x != p[x]) {
        x = p[x];
   }

   return x;
}

void Union(int x, int y) { //uneste arborii cu radacinile x si y
    x = find(x);
    y = find(y);

    if(x != y) {
        if(sz[x] < sz[y]) {
            p[x] = y;
            sz[y] += sz[x];
        } else {
            p[y] = x;
            sz[x] += sz[y];
        }
    }
   
}

bool cmp(muchie a, muchie b) {
    return a.c < b.c;
}

int main() {

    int n, m, nr = 0;
    fin >> n >> m;
    for(int i = 1; i <= n; i++) {
        p[i] = i;
        sz[i] = 1;
    }

    for(int i = 1; i <= m; i++) {
       fin >> v[i].x >> v[i].y >> v[i].c;
    }
    sort(v + 1, v + m + 1, cmp);

    int apm = 0;

    for(int i = 1; i <= m; i++) {
        if(find(v[i].x) != find(v[i].y)) {
            apm += v[i].c;
            Union(v[i].x, v[i].y);
            sol[++nr] = v[i];
        }
    }

    fout << apm << '\n' << nr << '\n';
    for(int i = 1; i <= nr; i++) {
        fout << sol[i].x << ' ' << sol[i].y << '\n';
    }

    fin.close();
    fout.close();
    return 0;

}