Cod sursa(job #744206)

Utilizator Marius_mFMI-M2 Marius Melemciuc Marius_m Data 8 mai 2012 00:11:24
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb

#include<iostream>
#include<cstdio>
#include<algorithm>

using namespace std;

const int Nmax1 = 200001;
const int Nmax2 = 400001;

typedef struct muchie { int x,y,cost; }MUCHIE;
MUCHIE v[Nmax2],APM[Nmax1];
int n,m,nr_APM,CostAPM;

int T[Nmax1],Rang[Nmax1];

FILE *in,*out;

void read()
{
	in=fopen("apm.in","r");
	out=fopen("apm.out","w");
	fscanf(in,"%d %d",&n,&m);
	for(int i = 1 ; i <= m ; i++)
		fscanf(in,"%d %d %d",&v[i].x,&v[i].y,&v[i].cost);
}

bool cmp(MUCHIE x,MUCHIE y)
{
	return (x.cost<y.cost);
}

void MakeSet(int x)
{
	T[x] = x;
	Rang[x] = 1;
}

int FindRoot(int x)
{
	int i,a;
	for(i = x ; T[i] != i ; i = T[i])
		;
	while(T[x] != x)
	{
		a = T[x];
		T[x] = i;
		x = a;
	}
	return i;
}

void Link(int x,int y)
{
	if(Rang[x] < Rang[y])
		T[x] = y;
	else
		if(Rang[x] > Rang[y])
			T[y] = x;
		else
		{
			T[x] = y;
			Rang[y]++;
		}
}


void Unite(int x,int y)
{
	Link(FindRoot(x),FindRoot(y));
}

void Solve()
{
	for(int i = 1 ; i <= n ; i++)
		MakeSet(i);
	sort(v+1,v+m+1,cmp);
	for(int i = 1 ; i <= m - 1 ; i++)
		if(FindRoot(v[i].x) != FindRoot(v[i].y))
		{
			nr_APM++;
			APM[nr_APM].x = v[i].x;
			APM[nr_APM].y = v[i].y;
			APM[nr_APM].cost = v[i].cost;
			CostAPM = CostAPM + v[i].cost;
			Unite(v[i].x,v[i].y);
		}
}

void printAPM()
{
	fprintf(out,"%d\n%d\n",CostAPM,n-1);
	for(int i = 1 ; i <= n - 1 ; i++)
		fprintf(out,"%d %d\n",APM[i].x,APM[i].y);
	fclose(in);
	fclose(out);
}

int main()
{
	nr_APM = 0;
	CostAPM = 0;
	read();
	Solve();
	printAPM();
	return 0;
}