Cod sursa(job #567684)

Utilizator iordacheinaiordache ina alexandra iordacheina Data 30 martie 2011 13:20:32
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include<fstream.h>
#include<stdlib.h>
#define NM 200001
#define NM 400001
#define endl "\n"

ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie{
			int x,y,c;
			};
int n,m,L[NM];
muchie v[NM],h[NM];

void citire(){
int i;
fin>>n>>m;
for(i=0;i<m;i++) fin>>v[i].x>>v[i].y>>v[i].c;
}

int fcmp(void const *a,void const *b){
return ((muchie*)a)->c-((muchie*)b)->c;
}


int min(int x,int y){
if(x<y) return x;
return y;
}

int max(int x,int y){
if(x>y) return x;
return y;
}

int find(int x){
if(x==L[x]) return x;
return find(L[x]);
}

void Union(int x,int y){
int px==find(x);
int py==find(y);
if(px<py) L[py]=px;
else L[px]=py;
}


int main(){
int i,ms=0,j,ct=0;
citire();
qsort(v,m,sizeof(v[0]),fcmp);
for(i=1;i<=n;i++) L[i]=i;
i=0;
while(ms<n-1){int px,py;
	 do{px=find(v[i].x);
			py=find(v[i].y);
			if(px==py) i++;
		 }while(px==py);
ms++;
ct+=v[i].c;
h[ms]=v[i];
int a=min(px,py);
int b=max(px,py)
Union(b,a);
	 }
fout<<ct<<endl<<n-1<<endl;
for(i=0;i<n-1;i++) fout<<h[i].x<<" "<<h[i].y<<endl;
return 0;
}