基本的并查集应用
#include <stdio.h>
#include <string.h>
#define MAX 50001
int father[MAX];
int Find(int x)
{
return father[x] ? father[x] = Find(father[x]) : x;
}
int Union(int x, int y)
{
int fx = Find(x), fy = Find(y);
if(fx == fy) return fx;
else return father[fy] = fx;
}
int main()
{
int test = 0, n, m;
int i, x, y, cnt;
scanf("%d", &test);
while(test--){
scanf("%d%d", &n, &m);
/* initialize */
memset(father, 0, sizeof(int) * (n + 1));
cnt = 0;
/* find and union */
for(i = 0; i < m; ++i){
scanf("%d%d", &x, &y);
Union(x, y);
}
/* count how many trees there are */
for(i = 1; i <= n; ++i){
if(Find(i) == i) ++cnt;/* if i is a root node */
}
printf("%d\n", cnt);
}
return 0;
}