HDU 1879 继续畅通工程

/*
思路:在qsort中,将已建数据排列到前面即可。
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int nMax = 107;
struct Node
{
	int x, y;
	int cost;
	int isBuild;
}node[nMax * nMax];
int p[nMax];
int N;
int find(int x)
{
	return p[x] == x ? x : p[x] = find(p[x]);
}
int cmp(const void *a, const void *b)
{
	Node *pa = (Node *) a;
	Node *pb = (Node *) b;
	if(pb->isBuild) return 1;
	if(pa->isBuild) return -1;
	return pa->cost - pb->cost;
}
void init()
{
	int i;
	int m = N * (N - 1) / 2;
	for(i = 0; i < m; ++ i)
		scanf("%d %d %d %d", &node[i].x, &node[i].y, &node[i].cost, &node[i].isBuild);
	for(i = 0; i <= N; ++ i)
		p[i] = i;
	qsort(node, m, sizeof(node[0]), cmp);
}
int main()
{
	//freopen("f://data.in", "r", stdin);
	while(scanf("%d", &N) && N)
	{
		init();
		int i;
		int m = N * (N - 1) / 2;
		int ans = 0;
		for(i = 0; i < m; ++ i)
		{
			int x = find(node[i].x);
			int y = find(node[i].y);
			if(x != y)
			{
				p[x] = y;
				if(!node[i].isBuild)
					ans += node[i].cost;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}

你可能感兴趣的:(struct)