pku 2524 Ubiquitous Religions

#include <stdio.h>
#include <string.h>
#define MAXN 50005
int father[MAXN];
inline int find(int x)
{
    int i,t;
    for(i=x; father[i]>0; i=father[i]) ;
    while(x!=i)
    {
        t=father[x];
        father[x]=i;
        x=t;
    }
    return i;
}
inline void merge(int x,int y)
{
    int fx=find(x),fy=find(y);
    if(fx==fy) return;
    if(father[fx]>father[fy])
    {
        father[fy]+=father[fx];
        father[fx]=fy;
    }
    else
    {
        father[fx]+=father[fy];
        father[fy]=fx;
    }
}
int main()
{
    int n,m,i,j,cas=1;
    while(scanf("%d %d",&n,&m),n+m)
    {
        memset(father,-1,sizeof(*father)*(n+1));
        while(m--)
        {
            scanf("%d %d",&i,&j);
            merge(i,j);
        }
        int cnt=0;
        for(i=1; i<=n; i++)
            if(father[i]<0) cnt++;
        printf("Case %d: %d\n",cas++,cnt);
    }
    return 0;
}

posted @ 2010-08-25 19:24  菜到不得鸟  阅读(79)  评论(0)    收藏  举报