并查集——HDU1213

第一次做并查集的题,选了道比较简单的。
用数组很简单,不多说了。

#include <cstdio>
#include <cstdlib>

int a[1010];

void Init(int N){
    for(int i = 1;i <= N;i++)
        a[i] = i;
}

int Find(int x){
    while(x != a[x])
        x = a[x];
    return x;
}

void Union(int x, int y){
    int x1 = Find(x);
    int y1 = Find(y);
    if(x1 != y1)
        a[y1] = x1;
    return ;
}

int main(){
    //freopen("in.txt","r",stdin);
    int T;
    scanf(" %d",&T);
    while(T--){
        int N,M;
        scanf(" %d%d",&N,&M);
        Init(N);
        for(int i = 0;i < M;i++){
            int x,y;
            scanf("%d%d",&x,&y);
            Union(x,y);
        }

        int ans = 0;
        for(int i = 1;i <= N;i++){
            if(i == a[i])
                ans++;
        }
        printf("%d
",ans);
        //getchar();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/sean10/p/4998038.html