http://acm.hdu.edu.cn/showproblem.php?pid=1213

并查集模板

#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 1005
using namespace std;
int father[maxn];
int isRoot[maxn];
int findFather(int x){
    if(father[x] == x) return x;
    else{
        int tp = findFather(father[x]);
        father[x] = tp;
        return tp;
    }
}
void Union(int a,int b){
    int faA = findFather(a);
    int faB = findFather(b);
    if(faA != faB)
        father[faA] = faB;
}
void init(int n){
    for(int i = 1;i <= n;i++){
        father[i] = i;
        isRoot[i] = 0;
    }
}
int main(){
    int T;
    scanf("%d",&T);
    for(int i = 0;i < T;i++){
        int M,N;
        scanf("%d%d",&M,&N);
        init(M);
        int x,y;
        while(N--){
            scanf("%d%d",&x,&y);
            Union(x,y);
        }       
    int ans = 0;
    for(int i = 1;i <= M; i++){
        isRoot[findFather(i)]++;
    }
    for(int i = 1;i <= M; i++){
        if(isRoot[i] != 0)
        ans++;
    }
    printf("%d\n",ans);
    }
    return 0;
}