http://acm.hdu.edu.cn/showproblem.php?pid=1213
并查集基础题,不做任何判断,最后只要统计有几个集合即可。
#include <stdio.h>
#define MAX 1001
int father[MAX];
int n, m;
void init()//初始化
{
int i;
for(i = 0; i <= n; i ++){
father[i] = i;
}
}
int getfather(int x)//查找父节点
{
while(x!=father[x])
x=father[x];
return x;
}
void join(int a, int b)//将新节点插入到并查集中
{
int fa = getfather(a);
int fb = getfather(b);
if(fa!=fb){
father[fb] = fa;
}
}
int main()
{
int cas, a, b, i;
int res;
while(scanf("%d", &cas)!=EOF){
while(cas--){
scanf("%d%d", &n, &m);
init();
res = 0;
while(m--){
scanf("%d%d", &a, &b);
join(a, b);
}
for(i = 1; i <= n; i ++){
if(father[i] == i)res ++;
}
printf("%d\n", res);
}
}
return 0;
}