Cod sursa(job #1039278)

Utilizator stefan.friptuPetru Stefan Friptu stefan.friptu Data 22 noiembrie 2013 19:03:50
Problema Arbore partial de cost minim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <cstdio>
#include <algorithm>

//75088, 75089,75090, 75062
using namespace std;

long i,j,n,m,h[200001],t[200001],muchii,cost;

struct nod {

    long x,y,c;
    bool viz;
};

nod a[400001];

bool cmp (nod a, nod b) {
    return a.c <b.c;
}

long find (long x) {
    while(t[x]!=x)
        x=t[x];
    return x;
}

void Union(long x, long y) {

    if(h[x]==h[y])
    {
        h[x]++;
        t[y]=x;
    }
    else if(h[x]<h[y])
    {
        t[x]=y;
    }
    else t[y]=x;
}

int main () {

    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);

    scanf("%ld%ld",&n,&m);

    for(i=1; i<=n; i++)
        t[i]=i,h[i]=1;

    for(i=1; i<=m; i++) {
        scanf("%ld%ld%ld",&a[i].x,&a[i].y,&a[i].c);

    }
    sort(a+1,a+m+1,cmp);

    for(i=1; i<=m && muchii<n; i++) {

        if(find(a[i].x)!=find(a[i].y)) {
            Union(find(a[i].x),find(a[i].y));
            muchii++;
            cost+=a[i].c;
            a[i].viz=1;
        }
    }
    printf("%ld\n%ld\n",cost,muchii);
    for(i=1; i<=muchii; i++) {
        if(a[i].viz)
            printf("%ld %ld\n",a[i].x,a[i].y);
    }
    return 0;
}