Cod sursa(job #910175)

Utilizator deresurobertoFMI - Deresu Roberto deresuroberto Data 10 martie 2013 19:23:02
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include<cstdio>
#include<algorithm>
using namespace std;
  
struct gr{
    int x;
    int y;
    int c;
}a[200005];
  
int n,m,i,j,x,y,c,t,t1,t2,viz[100005],v1[100005],v2[100005];
  
int cmp(const gr a1,const gr b)
{
    return a1.c<b.c;
}
  
void citire()
{
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    scanf("%d %d",&n,&m);
    for(i=1;i<=m;i++){
        scanf("%d %d %d",&x,&y,&c);
        a[i].x=x;
        a[i].y=y;
        a[i].c=c;
		viz[i]=i;
    }
}
  
  
void ver()
{
	bool ok;
    t=x;ok=true;
    while(t!=viz[t] && ok){
		t=viz[t];
		if(viz[t]==y)ok=false;
	}
	if(ok){
    t1=t;
    t=y;
    while(t!=viz[t])t=viz[t];
    t2=t;
	}
	else t1=t2=1;
	
}
  
int main()
{
    citire();
    sort(a+1,a+m+1,cmp);
	j=0;i=0;c=0;
	
    while (i<=m && j!=n-1){
		i++;
        x=a[i].x;
        y=a[i].y;
        ver();
        if(t1!=t2){
            j++;
            c=c+a[i].c;
            v1[j]=x;
            v2[j]=y;
            viz[t2]=viz[t1];
        }
    }
	
    printf("%d\n",c);
    printf("%d\n",n-1);
    for(i=1;i<=n-1;i++)printf("%d %d\n",v1[i],v2[i]);
    return 0;
}