Cod sursa(job #2000451)

Utilizator ana_dariaAna Daria Hendoreanu ana_daria Data 13 iulie 2017 18:15:36
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
const int nmax=200000;
int t[nmax+3],h[nmax+3];
struct muchie{int x,y,cost;};
muchie v[nmax+3];
int findset(int x)
{
    while(t[x]!=x)
        x=t[x];
    return x;
}
void unionset(int x, int y)
{
    if(h[x]==h[y])
    {
        h[x]++;
        t[y]=x;
    }
    else if(h[x]>h[y]) t[y]=x;
        else t[x]=y;
}
bool cmp(muchie a, muchie b)
{
    return a.cost<b.cost;
}
muchie sol[nmax];
int main()
{
    int n,m,cmin=0,i,nr=0,a,b;
    fin>>n>>m;
    for(i=1;i<=m;i++)
    {
        fin>>v[i].x>>v[i].y>>v[i].cost;
    }
    sort(v+1,v+m+1,cmp);
    for(i=1;i<=n;i++)
    {
        t[i]=i;
        h[i]=1;
    }
    for(i=1;i<=m&&nr<=n-1;i++)
    {
        a=findset(v[i].x);
        b=findset(v[i].y);
        if(a!=b)
        {
            unionset(a,b);
            cmin+=v[i].cost;
            nr++;
            sol[nr].x=v[i].x;
            sol[nr].y=v[i].y;
        }
    }
    fout<<cmin<<"\n"<<n-1<<"\n";
    for(i=1;i<=n-1;i++)
        fout<<sol[i].x<<" "<<sol[i].y<<"\n";
    return 0;
}