Cod sursa(job #655158)

Utilizator titeltitel popescu titel Data 1 ianuarie 2012 16:12:57
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
// Kruskal de *** puncte
#include <fstream>
#include <algorithm>
#define nmax 200001
#define mmax 400001
using namespace std;
ifstream f("apm.in"); ofstream g("apm.out");
int N, M, i, j, t1, t2, nr, cost;
int tata[nmax], sol[nmax];
int x[mmax], y[mmax], c[mmax], ind[mmax];
int cmp(int a, int b) {return (c[a]<c[b]);}
int find(int x)
{	if (x!=tata[x]) tata[x]=find(tata[x]);
	return tata[x];
}
void unite(int i, int j){tata[i]=j;}
int main()
{	f>>N>>M;
	for (i=1;i<=M;++i) {f>>x[i]>>y[i]>>c[i]; ind[i]=i;}
	for (i=1;i<=N;++i) tata[i]=i;
	sort(ind+1,ind+M+1,cmp);
	for (i=1; i<=M && nr<N-1; ++i)
		{t1=find(x[ind[i]]); t2=find(y[ind[i]]);
		 if (t1!=t2) {unite(t1,t2); cost+=c[ind[i]]; sol[++nr]=ind[i];}
		}
	g<<cost<<'\n'<<nr<<'\n';
	for (i=1;i<=nr;++i) g<<x[sol[i]]<<' '<<y[sol[i]]<<'\n';	
	return 0;
}