HDU 1232 畅通工程 (并查集)

HDU 1232


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n, m;
int father[1010];
int find(int t) {
	if(father[t] == -1) return t;
	return father[t] = find(father[t]);
}
void merge(int a, int b) {
	int t1, t2;
	t1 = find(a);
	t2 = find(b);
	if(t1 != t2) {
		father[t1] = t2;
	}
}
int main () {
	while(~scanf("%d", &n) && n) {
		scanf("%d", &m);
		int i;
		for(i = 1; i <= n; i++) {
			father[i] = -1;
		}
		while(m--) {
			int a, b;
			scanf("%d %d", &a, &b);
			merge(a, b);
		}
		int ans = 0;
		for(i = 1; i <= n; i++) {
			if(father[i] == -1) ans++;
		}
		printf("%d\n", ans - 1);
	}
	return 0;
}


你可能感兴趣的:(HDU 1232 畅通工程 (并查集))