poj 2524

来源:互联网 发布:国外数据可视化公司 编辑:程序博客网 时间:2024/06/06 02:10

并查集  水题


#include<stdio.h>

#define MAX 100005
int father[MAX];


int count;


int Find_Set(int x)
{
    if(x!=father[x])
    {
        father[x]=Find_Set(father[x]);
    }
    return father[x];
}


void Union(int x,int y)
{
    x=Find_Set(x);
    y=Find_Set(y);
    if(x!=y)
    father[x]=y;
}




int main()
 {
    int n,m,i,x,y,count,num=1;
    while(scanf("%d%d",&n,&m),n||m)
    {
        count=0;
         for(i=1;i<=n;i++)
          father[i]=i;
        for(i=0;i<m;i++)
        {
             scanf("%d%d",&x,&y);
        Union(x,y);
        }
        for(i=1;i<=n;i++)
        {
            if(father[i]==i)
            count++;
        }
       printf("Case %d: %d\n",num++,count);
    }
    return 0;
 }