Cod sursa(job #832432)

Utilizator Sanduleac_VladSanduleac Vllad Alexandru Sanduleac_Vlad Data 10 decembrie 2012 17:07:13
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <stdio.h>
#include <algorithm>
using namespace std;

long N, M, totc;

struct L {
	long x, y, c;
} v[400001];

long h[200001], f[200001];
bool acc[400001];

bool cmp(L l1, L l2) {
	return l1.c < l2.c;
}

long find(long x) {
	if(f[x] == x || f[x] == 0)
		return x;
	else return find(f[x]);
}

void unite(long x, long y, long cost) {
	x = find(x);
	y = find(y);
	if(x == y)
		return;
	if(h[x] == h[y]) {
		f[y] = x;
		h[x]++;
	}
	else if(h[x] > h[y])
		f[y] = x;
	else f[x] = y;
	totc += cost;
}

int main() {
	long i, j, x, y, c, ci;
	freopen("apm.in", "r", stdin);
	freopen("apm.out", "w", stdout);
	scanf("%ld %ld", &N, &M); 
	for(i = 1; i <= M; i++) {
		scanf("%ld %ld %ld", &x, &y, &c);
		v[i].x = x;
		v[i].y = y;
		v[i].c = c;
	}
	sort(v + 1, v + M + 1, cmp);
	for(i = 1; i <= N; i++) {
		ci = totc;
		unite(v[i].x, v[i].y, v[i].c);
		if(ci != totc)
			acc[i] = 1;
	}
	printf("%ld\n", totc);
	for(i = 1; i <= N; i++)
		if(acc[i])
			printf("%ld %ld\n", v[i].x, v[i].y);
	return 0;
}