Cod sursa(job #3321773)

Utilizator temp1234Temp Mail temp1234 Data 11 noiembrie 2025 12:34:04
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, x, y, c;

struct muchie{
    int first, second, cost;
};

vector<muchie> l;
vector<int> p, h;

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

int main() {
    fin >> n >> m;
    for(int i = 1; i <= m; i ++){
        fin >> x >> y >> c;
        l.push_back({x, y, c});
    }

    sort(l.begin(), l.end(), [](muchie a, muchie b){
        return a.cost < b.cost;
    });

    p.resize(m + 1);
    h.resize(m + 1);
    for(int i = 1; i <= n; i ++) {
        p[i] = i;
        h[i] = 1;
    }

    int sol = 0;
    vector< pair<int, int> > K;

    for(auto e : l) {
        x = e.first, y = e.second, c = e.cost;
        if(Find(x) != Find(y)) {
            sol += c;
            K.push_back({x, y});
            Union(x, y);
        }
    }

    fout << sol << '\n' << K.size() << '\n';
    for(auto e : K) {
        fout << e.first << ' ' << e.second << '\n';
    } 

    return 0;
}