HDU 1232 并查集裸题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35346829/article/details/53841212
#include<iostream>
#include<cstdio>
using namespace std;
int N,M;
int father[1005];
int find(int x){
    if(x == father[x]) return x;
    else return father[x] = find(father[x]);
}
int main(){
    while(scanf("%d",&N) != EOF){
        if(N == 0) break;
        scanf("%d",&M);
        for(int i = 1;i <= N;++i) father[i] = i;
        int x,y;
        int ans = N-1;
        for(int i = 0;i < M;++i){
            scanf("%d%d",&x,&y);
            if(find(x) == find(y)) continue;
            ans --;
            father[find(x)] = find(y);
        }
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35346829/article/details/53841212