ZOJ 3204 Connect them【kruskal】

【WA了好多次,不过值了,对于kruskal和prim都有进一步的了解
//2622383 	2011-08-11 11:11:35 	Accepted 	            3204 	C++ 	130 	240 	ylwh!
//2622381 	2011-08-11 11:10:47 	Compilation Error 	    3204 	C++ 	0 	    0 	    ylwh!
//2622357 	2011-08-11 10:54:31 	Wrong Answer 	        3204 	C++ 	100 	240 	ylwh!
//2621861 	2011-08-10 19:33:12 	Wrong Answer 	        3204 	C++ 	120 	240 	ylwh!
//2621847 	2011-08-10 19:20:04 	Wrong Answer 	        3204 	C++ 	130 	240 	ylwh!
//2621792 	2011-08-10 18:13:06 	Wrong Answer 	        3204 	C++ 	140 	240 	ylwh!
//2621689 	2011-08-10 17:04:17 	Wrong Answer 	        3204 	C++ 	80 	    180 	ylwh!
//2621674 	2011-08-10 16:59:52 	Wrong Answer 	        3204 	C++ 	80 	    180 	ylwh!
//2621645 	2011-08-10 16:49:25 	Wrong Answer 	        3204 	C++ 	100 	180 	ylwh!
//2621638 	2011-08-10 16:47:32 	Wrong Answer 	        3204 	C++ 	80 	    180 	ylwh!
//2621613 	2011-08-10 16:36:01 	Time Limit Exceeded 	3204 	C++ 	1001 	176 	ylwh!
//2621597 	2011-08-10 16:26:16 	Time Limit Exceeded 	3204 	C++ 	1001 	176 	ylwh!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <algorithm>
#define N 101
using namespace std;
struct node
{
    int num, root;
} s[N];
struct edge
{
	int x, y, len;
}e[N*N/2];
int cmp(struct edge a, struct edge b)
{
    if(a.len != b.len)
        return a.len < b.len;
    else if(a.x != b.x)
        return a.x < b.x;
	else
		return a.y < b.y;
}
int cmp2(struct edge a, struct edge b)
{
	if(a.x != b.x)
		return a.x < b.x;
	else
		return a.y < b.y;
}
int find_root(int x)
{
	while(x != s[x].root)
		x = s[x].root;
	return x;
}
int main(void)
{
	int n, c[N][N], t, i, j, cnt, a, b, ts;
	scanf("%d", &t);
	while(t--)
	{
		scanf("%d", &n);
		cnt = -1;
		ts = 0;
		for(i=1; i<=n; i++)
		{
			s[i].root = i;
			s[i].num = i;
			for(j=1; j<=i; j++)
				scanf("%d", &c[i][j]);
			for(j=i+1; j<=n; j++)
			{
				scanf("%d", &c[i][j]);
				if(c[i][j])
				{
					e[++cnt].x = i;
					e[cnt].y = j;
					e[cnt].len  = c[i][j];
				}
			}
		}
		sort(e, e+cnt+1, cmp);
		int top=0;
		for(i=0; i<=cnt; i++)
		{
			a = find_root(e[i].x);
			s[e[i].x].root = a;
			b = find_root(e[i].y);
			s[e[i].y].root = b;
			if(a != b)
			{
				s[b].root = a;
				if(e[i].x > e[i].y)
				{
					e[top].x = e[i].y;
					e[top].y = e[i].x;
				}
				else
				{
					e[top].x = e[i].x;
					e[top].y = e[i].y;
				}
				top++;
				ts++;
			}
		}
		if(ts != n-1)
		{
			printf("-1\n");
			continue;
		}
		sort(e, e+top, cmp2);
		printf("%d %d", e[0].x, e[0].y);
		for(i=1; i<top; i++)
			printf(" %d %d", e[i].x, e[i].y);
		printf("\n");
	}
    return 0;
}


你可能感兴趣的:(c,struct,IE,compilation)