HDU1213 http://acm.hdu.edu.cn/showproblem.php?pid=1213
题目大意:
并查集,只要找到所有父亲节点的个数即可。
AC代码:
#include <iostream>
using namespace std;
const int maxn = 5005;
int father[maxn];
void init() {
for(int i = 0 ; i < maxn ; i++) {
father[i] = i;
}
}
int find(int x) {
return father[x] == x ? x : find(father[x]);
}
int check(int x,int y) {
return find(x) == find(y);
}
void unionn(int x,int y) {
int p1 = find(x),p2 = find(y);
if(p1==p2) return;
father[p1] = p2;
}
int main() {
int t;
cin >> t;
while(t--) {
int sum = 0;
init();
int n,m;
cin >> n >> m;
for(int i = 0; i < m; i++) {
int a,b;
cin >> a >> b;
unionn(a,b);
}
for(int i = 1; i <= n;i++) {
if(father[i] == i) sum++;
}
cout << sum << endl;
}
return 0;
}