Cod sursa(job #3320186)

Utilizator adistancu10Stancu Adrian adistancu10 Data 4 noiembrie 2025 14:59:34
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <utility>

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.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;
    fin >> n >> m;

    for (int i=1; i<=m; i++){
        int x,y,c;
        fin >> 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);
        }
    }

    fout << sol << "\n";
    fout << a.size() << "\n";

    for (auto& i : a){
        fout << i.second << " " << i.first << "\n";
    }
}