Cod sursa(job #557302)

Utilizator rares192Preda Rares Mihai rares192 Data 16 martie 2011 16:02:41
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;

void Read();
void Kruskall();
void Write();
int Find(int );
void Union(int x, int y);

int cost, n, m, k;
int t[400001], h[400001];
struct muchie
{
	int x, y, c;
} a[400001];

vector< pair<int, int> > M;

bool Pred(muchie a, muchie b)
{
	return a.c < b.c;
}

int main()
{
	Read();
	Kruskall();
	Write();
	return 0;
}

void Read()
{
	ifstream fin("apm.in");
	
	fin >> n >> m;
	M.resize(n+1);
	
	int x, y, c;
	for(int i = 1; i <= m; ++i)
	{
		if( i <= n ) t[i] = i;
		fin >> x >> y >> c;
		a[i].x = x;
		a[i].y = y;
		a[i].c = c;
	}
	
	fin.close();
}

void Kruskall()
{
	sort(a + 1, a + m + 1, Pred);
	
	for(int i = 1; i <= m && k < n - 1; ++i)
	{
		int v1 = Find( a[i].x );
		int v2 = Find( a[i].y );
		
		if( v1 != v2)
		{
			cost += a[i].c;
			M[++k] = make_pair( a[i].x , a[i].y );
			
			Union(v1, v2);
		}
	}
}

int Find(int x)
{
	if( x != t[x] )
		t[x] = Find( t[x] );
	return t[x];
}

void Union(int x, int y)
{
	if( h[x] > h[y] )
		t[y] = x;
	else
	{
		t[x] = y;
		if( h[x] == h[y] )
			++h[y];
	}
}

void Write()
{
	ofstream fout("apm.out");
	
	fout << cost << "\n" << n-1 <<"\n";
	
	for(int i = 1; i <= n -1; ++i)
		fout << M[i].first << " "<< M[i].second << '\n';
}