Cod sursa(job #1039248)

Utilizator multislashRobert Morosanu multislash Data 22 noiembrie 2013 18:30:42
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
//Algoritmul lui Kruskal
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,ml,cost,afis,i,t[200001],h[200001];
bool viz[400001];
int father(int x)
{
    while(t[x]!=x) x=t[x];
    return x;
}
void unire(int x,int y)
{
    if(h[x]==h[y])
    {
        h[x]++;
        t[y]=x;
    }
    else if(h[x]<h[y])
    {
        t[x]=y;
    }
    else t[y]=x;
}
struct NOD
{
    int x,y,c;
};
NOD v[200001];
bool cmp(NOD a,NOD b)
{
    return a.c<b.c;
}
int main()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++) t[i]=i;
    for(i=1;i<=n;i++) h[i]=1;
    for(i=1;i<=m;i++)
    {
        scanf("%d%d%d",&v[i].x,&v[i].y,&v[i].c);
    }
    sort(v+1,v+m+1,cmp);
    for(i=1;i<=m&&ml<n;i++)
    {
        if(father(v[i].x)!=father(v[i].y))
        {
            unire(father(v[i].x),father(v[i].y));
            cost=cost+v[i].c;
            viz[i]=1;
            ml++;
        }
    }
    printf("%d\n",cost);
    printf("%d\n",ml);
    for(i=1;i<=m&&afis<=ml;i++)
    {
        if(viz[i]==1)
        {
            afis++;
            printf("%d %d\n",v[i].x,v[i].y);
        }
    }
    return 0;
}