Cod sursa(job #3370533)

Utilizator andreiapPopescu Andrei andreiap Data 26 octombrie 2026 14:50:49
Problema Arbore partial de cost minim Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h> 
#include <fstream>
using namespace std;

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

int p[200001], sz[200001];


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 (sz[x] > sz[y]) {
        p[y] = x;
        sz[x] += sz[y];
    } else {
        p[x] = y;
        sz[y] += sz[x];
    }
}

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

muchie v[400001], r[400001];


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


//! ALGORITMUL LUI KRUSCAL
int main() {
    int n, m;
    f >> n >> m;
    for (int i = 1; i<= n; i++) {
        p[i] = i;
        sz[i] = i;
    }

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

    sort(v + 1, v + m + 1, cmp);
    int sum = 0;
    int nr = 0;
    for (int i = 1; i <= m; i++ ) {
        if (Find(v[i].x) != Find(v[i].y)) {
            nr ++;
            r[nr] = v[i];
            sum += v[i].c;
            Union(v[i].x, v[i].y);
        }
    }

    g << sum << '\n';
    g << nr <<'\n';
    for (int i = 1; i <= nr; i ++) {
        g << r[i].y << " " << r[i].x << '\n';
    }

    return 0;
}