首页 > 其他 > 详细

并查集 试水 hdu1232

时间:2018-11-08 21:16:05      阅读:171      评论:0      收藏:0      [点我收藏+]
技术分享图片
#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

 

并查集 试水 hdu1232

原文:https://www.cnblogs.com/clljs/p/9931838.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!