POJ-2421(最小生成树模版)(Constructing Roads )

int p[10001];
int rank[10001];
void make_set(int x) {
	p[x] = x;
	rank[x] = 0;
}
int find_set(int x) {
	if (x != p[x])
		p[x] = find_set(p[x]);
	return p[x];
}
void link(int x, int y) {
	if (rank[x] > rank[y]) p[y] = x;
	else {
		p[x] = y;
		if (rank[x] == rank[y])
			rank[y]++;
	}
}
void union_set(int x, int y) {
	link(find_set(x), find_set(y));
}
struct my
{
	int x, y, z;
} wo[10005];
bool cmp(my a, my b)
{
	return a.z < b.z;
}
int main()
{
	int n;
	while (scanf("%d", &n) == 1) {
		int i, j, a, b;
		int index = 0;
		for (i = 0; i < n; ++i) {
			for (j = 0; j < n; ++j) {
				scanf("%d", &a);
				if (i < j) {
					wo[index].x = i;
					wo[index].y = j;
					wo[index].z = a;
					++index;
				}
			}
		}
		for (i = 0; i < n; ++i) make_set(i);
		sort(wo, wo + index, cmp);
		scanf("%d", &b);
		for (i = 0; i < b; ++i) {
			int x, y;
			scanf("%d%d", &x, &y);
			union_set(x - 1, y - 1);
		}
		int ans = 0;
		for (i = 0; i < index; ++i) {
			if (find_set(wo[i].x) != find_set(wo[i].y)) {
				ans += wo[i].z;
				union_set(wo[i].x, wo[i].y);
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}


你可能感兴趣的:(算法模板)