Cod sursa(job #1999126)

Utilizator mihai2003LLL LLL mihai2003 Data 10 iulie 2017 13:06:59
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <map>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
bool v[400001];
struct muchie{
    int first,second;
    int cost;
}cost[400001];
int t[200001],h[200001];
int findset(int x){
    while(x!=t[x])
        x=t[x];
    return x;
}
bool unionset(int x,int y){
    int tx=findset(x),ty=findset(y);
    if(tx==ty)return 0;
    if(h[tx]==h[ty]){
        h[tx]++;
        t[ty]=tx;
    }
    else
        if(h[tx]<=h[ty])
            t[tx]=ty;
        else
            t[ty]=tx;
    return 1;
}
bool cmp(muchie a,muchie b){
    return (a.cost<b.cost);
}
int main()
{
    int n,m,a,b,c,costy=0,nr=0;
    in>>n>>m;
    for(int i=1;i<=m;i++){
        in>>cost[i].first>>cost[i].second>>cost[i].cost;
    }
    for(int i=1;i<=n;i++)
        h[i]=1,t[i]=i;
    sort(cost+1,cost+m+1,cmp);
    for(int i=1;i<=m;i++){
        if(nr==n-1){
            out<<n-1<<endl<<costy<<endl;
            for(int j=1;j<=m;j++)
                if(v[j]==1)
                    out<<cost[j].first<<" "<<cost[j].second<<endl;
            return 0;
        }
        if(nr<=n-1)
            if(unionset(cost[i].first,cost[i].second)==1)
                nr++,costy+=cost[i].cost,v[i]=1;
    }
    out<<costy;
    return 0;
}