并查集 试水 hdu1232

#include <stdio.h>
#include <stdlib.h>
int n,m;
int father[1000],rank[1000];
int count;

int find(int x)
{
    if(father[x]==x) return x;
        else return father[x]=find(father[x]);
}
void unit(int x,int y)
{
    x=find(x);
    y=find(y);
    if(x==y) return;

    if(rank[x]<rank[y]){
        father[x]=y;
        count--;
    }else{
            father[y]=x;
            if(rank[x]==rank[y]) rank[x]++;
            count--;
    }
}
int main()
{
    while(scanf("%d",&n)==1){
        if(n==0) break;
        scanf("%d",&m);
        count=n;
        int i;
        //初始化
        for(i=0;i<n;i++){
            father[i]=i;
            rank[i]=0;
        }
        int x,y;
        for(i=0;i<m;i++){
            scanf("%d%d",&x,&y);
            unit(x-1,y-1);
        }
        printf("%d\n",count-1);
    }
    return 0;
}
View Code

 

posted @ 2018-11-08 20:30  北梗  阅读(94)  评论(0编辑  收藏  举报