Cod sursa(job #663060)

Utilizator hunter_ionutzzzFarcas Ionut hunter_ionutzzz Data 17 ianuarie 2012 19:26:05
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include<fstream>
#include<algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
typedef struct{int x,y,cost;}cel;
typedef struct{int x,y;}cel1;
int i,n,m,n1,cost,muchie,aux1,aux2,par[2000001],grad[200001];
cel v[400001],aux;
cel1 rasp[200001];

struct cmp
{   bool operator()(const cel &a, const cel &b)const
    { 
          if(a.cost <  b.cost) return 1;
          return 0;
    }
};
int main()
{   fin >> n >> m;
    for (i=1;i<=m;++i)
	{   fin >> v[i].x >> v[i].y >> v[i].cost;
	    par[i] = i;
		grad[i] = 1;
	}
	sort(v+1,v+1+m,cmp());
	n1 = n;
	for (i=1;i<=m && muchie < n1-1;++i)
	{   aux1 = v[i].x;
	    aux2 = v[i].y;
		while (aux1 != par[aux1])
			aux1 = par[aux1];
		while (aux2 != par[aux2])
			aux2 = par[aux2];
		if (aux1 != aux2)
		{   ++muchie;
		    rasp[muchie].y = v[i].x;
			rasp[muchie].x = v[i].y;
		    cost = cost + v[i].cost;
			if (grad[aux1] < grad[aux2])
				par[aux1] = aux2;
			else
				if (grad[aux1] > grad[aux2])
					par[aux2] = aux1;
				else
				{   ++grad[aux1];
				    par[aux2] = aux1;
				}
		}
	}
	--n1;
	fout << cost << '\n' << n1 << '\n';
	for (i=1;i<=n1;++i)
		fout << rasp[i].x << " " << rasp[i].y << '\n';
	
	return 0;
}