Cod sursa(job #639600)

Utilizator cosmin79Carabet Cosmin Andrei cosmin79 Data 23 noiembrie 2011 17:17:44
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
#define NMAX 200001
using namespace std;
int n,m,rad[NMAX],grd[NMAX],cost_f,r;
struct muchie
{
	int a,b,c;
};
muchie A[NMAX],B[NMAX];
void read()
{
	scanf("%d%d",&n,&m);
	int i,x,y,z;
	for (i=1; i<=m; i++)
	{
		scanf("%d%d%d",&x,&y,&z);
		A[i].a=x; A[i].b=y; A[i].c=z;
	}
}
bool comp(muchie x,muchie y)
{
	if (x.c<y.c)
		return 1;
	return 0;
}
void init()
{
	int i;
	for (i=1; i<=n; i++)
		rad[i]=i,grd[i]=1;
}
int root(int x)
{
	int nod=x,act;
	while (rad[nod]!=nod)
		nod=rad[nod];
	while (rad[x]!=x)
	{
		act=rad[x];
		rad[x]=nod;
		x=act;
	}
	return nod;
}
void unire(int x,int y)
{
	rad[x]=y;
}
void solve()
{
	int i;
	init();
	for (i=1; i<=m; i++)
		if (root(A[i].a)!=root(A[i].b))
		{
			B[++r].a=A[i].a; B[r].b=A[i].b;
			cost_f+=A[i].c;
			unire(rad[A[i].a],rad[A[i].b]);
		} 
}
void reconst()
{
	int i;
	printf("%d\n",r);
	for (i=1; i<=r; i++)
		printf("%d %d\n",B[i].a,B[i].b);
}
int main()
{
	freopen("apm.in","r",stdin);
	freopen("apm.out","w",stdout);
	read();
	sort(A+1,A+m+1,comp);
	solve();
	printf("%d\n",cost_f);
	reconst();
	return 0;
}