Cod sursa(job #1688410)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 13 aprilie 2016 14:45:07
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>

#define NMax 200005
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");

struct muchie{
    int x,y,c;
}M[NMax * 2];

int n,nr,s,m,vf1,vf2;
int root[NMax],rang[NMax],sol[NMax];

bool cmp(muchie x,muchie y){
    return (x.c < y.c);
}
int rad(int x){
    while(root[x] != x){
        x = root[x];
    }
    return x;
}
int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
        f >> M[i].x >> M[i].y >> M[i].c;
    sort(M + 1, M + 1 + m,cmp);
    for(int i = 1; i <= n; ++i){
        root[i] = i;
        rang[i] = 1;
    }
    for(int i = 1; i <= m && nr < n - 1; ++i){
        vf1 = rad(M[i].x);
        vf2 = rad(M[i].y);
        if(vf1 != vf2){
            nr++;
            s += M[i].c;
            sol[nr] = i;
            if(rang[vf1] > rang[vf2]){
                rang[vf1] += rang[vf2];
                root[vf2] = vf1;
            }else{
                rang[vf2] += rang[vf1];
                root[vf1] = vf2;
            }
        }
    }
    g << s << '\n' << nr << '\n';
    for(int i = 1; i <= nr; ++i){
        g << M[sol[i]].x << ' ' << M[sol[i]].y << '\n';
    }
    return 0;
}