Cod sursa(job #302857)

Utilizator hasegandaniHasegan Daniel hasegandani Data 9 aprilie 2009 12:39:07
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include<stdio.h>
#define nmax 200001
#define mmax 400001

struct muchie
{
    int x,y,cost,valid;
} v[mmax];

int t[nmax],n,m,sum;

void sort(int,int);

int up(int k)
{
    for(;t[k];k=t[k]);
    return k;
}

void kruskal()
{
    for(int i=1;i<=m;++i)
        if (up(v[i].x)!=up(v[i].y))
            {
                v[i].valid=1;
                sum+=v[i].cost;
                t[up(v[i].y)]=v[i].x;
            }
}

int main()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;++i)
        scanf("%d%d%d",&v[i].x,&v[i].y,&v[i].cost);
    sort(1,m);
    kruskal();
    printf("%d\n%d\n",sum,n-1);
    for(int i=1;i<=m;++i)
        if (v[i].valid)
            printf("%d %d\n",v[i].x,v[i].y);
    return 0;
}

void sort(int st,int dr)
{
    int poz=st-1;
    for(int i=st;i<=dr;++i)
        if (v[i].cost<=v[dr].cost)
            {
                muchie aux=v[i];
                v[i]=v[++poz];
                v[poz]=aux;
            }
    if (st<poz-1)
        sort(st,poz-1);
    if (poz+1<dr)
        sort(poz+1,dr);
}