简单并差集(hdu1232)

这就是赤果果的并差集啊,学并差集第一道做的就是做这道,直接代码。

#include <cstdio>
int bin[1002];
int findx(int x)
{
    int r=x;
    while(bin[r] !=r)
        r=bin[r];
    return r;
}
void merge(int x,int y)   //并集合
{
    int fx,fy;
    fx = findx(x);
    fy = findx(y);
    if(fx != fy)
        bin[fx] = fy;
}
int main()
{
    int n,m,i,x,y,count;
    while(scanf("%d",&n),n)
    {
        for(i=1;i<=n;i++)  //初始化
            bin[i] = i;
        for(scanf("%d",&m);m>0;m--)
        {
            scanf("%d %d",&x,&y);
            merge(x,y);
        }
        for(count=-1, i=1;i<=n;i++)
            if(bin[i] == i)
                count ++;
        printf("%d\n",count);
    }
}

 

posted on 2013-12-03 17:41  Arthas0v0  阅读(141)  评论(0编辑  收藏  举报

导航