zoj 1542 Network【kruskal】

//2605186 	2011-07-29 15:33:54 	Accepted 	1542 	C++ 	60 	416 	ylwh!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <algorithm>
#define N 1001
#define M 15001
using namespace std;
struct edge
{
	int x, y, len;
}connect[M];
typedef struct edge NODE;
int m, n, root[N], cmax, pcount, put[M];

bool cmp(const struct edge a, const struct edge b)
{
	return a.len < b.len;
}
	
void input()
{
	int i, j;
	for(i=1; i<=m; i++)
		scanf("%d%d%d", &connect[i].x, &connect[i].y, &connect[i].len);
}

void MAKE_SET()
{
	int i;
	for(i=1; i<=n; i++)
		root[i] = i;
}

int FIND_SET(int x)
{
	while(x != root[x])
		x = root[x];
	return x;
}

void kruskal()
{
	int i, a, b;
	pcount = 0, cmax = 0;
	MAKE_SET();
	sort(connect+1, connect+m+1, cmp);

	for(i=1; i<=m; i++)
	{
		a = FIND_SET( connect[i].x );
		b = FIND_SET( connect[i].y );
		if( a != b )
		{
			root[ b ] = a ;
			put[ pcount++ ] = i;
			if(connect[i].len  > cmax)
				cmax = connect[i].len;
		}
	}
}
void output()
{
	int i;
	printf("%d\n%d\n", cmax, pcount);
	for(i=0; i<pcount; i++)
		printf("%d %d\n", connect[ put[i] ].x, connect[ put[i] ].y);
}
		
int main()
{
	while(scanf("%d%d", &n, &m) != EOF)
	{
		input();
		kruskal();
		output();
	}
    return 0;
}

仿学姐的代码写的,学姐写的太好了··崇拜ing...学姐的代码http://blog.csdn.net/zxy_snow/article/details/6039453

你可能感兴趣的:(zoj 1542 Network【kruskal】)