Cod sursa(job #3165931)

Utilizator PescarusTanislav Luca Andrei Pescarus Data 7 noiembrie 2023 10:37:59
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <algorithm>

using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
const int nmax = 200005;

struct node{
    int a, b, cost;
};
bool comp(node m, node p){
    return m.cost < p.cost;
}
node v[400005];
int X[nmax], Y[nmax];
int father[nmax];
int n, m;
int gaseste_tatal(int x){
    if(father[x] < 0){
        return x;
    }
    int root = gaseste_tatal(father[x]);
    father[x] = root;
    return root;
}
void unite(int x, int y){
    int r_x = gaseste_tatal(x);
    int r_y = gaseste_tatal(y);
    if(father[r_x] < father[r_y]){
        swap(r_x, r_y);
    }
    father[r_y] += father[r_x];
    father[r_x] = r_y;
}
int main(){
    f >> n >> m;
    int len = 0;
    int cost_minim = 0;
    for(int i = 1; i <= n; i++){
        father[n] = -1;
    }
    for(int i = 1; i <= m; i++){
        f >> v[i].a >> v[i].b >> v[i].cost;
    }
    sort(v + 1, v + m + 1, comp);
    for(int i = 1; i <= m; i++){
        int r_a = gaseste_tatal(v[i].a);
        int r_b = gaseste_tatal(v[i].b);
        if(r_a != r_b){
            len++;
            X[len] = v[i].a;
            Y[len] = v[i].b;
            cost_minim = v[i].cost;
            unite(v[i].a, v[i].b);
        }
    }
    g << cost_minim << '\n' << len << '\n';
    for(int i = 1; i <= len; i++){
        g << X[i] << ' ' << Y[i] << '\n';
    }
}