hdu 2473 并查集的删除关系

      

View Code
#include<stdio.h>
#include<string.h>
int n,m;
int p[1101000];
int id[1101000];
int vis[1100010];
void init()
{
    int i;
    memset(vis,0,sizeof(vis));
    for(i=0;i<=n;i++)
    {
        p[i]=i;
        id[i]=i;
    }
}
int find(int x)
{
    return x==p[x]?x:p[x]=find(p[x]);
}
void unio(int x,int y)
{
int tx=find(x);
    int ty=find(y);
    if(tx!=ty)
    {
        p[ty]=tx;
    }
}
int main()
{
    int i,j;
    int a,b;
    int cases=1;
    char str[5];
while(scanf("%d%d",&n,&m)!=EOF)
    {
        init();
        int tn=n;
        int ans=0;
        if(n==0&&m==0) break;
while(m--)
        {
            scanf("%s",str);
            if(str[0]=='M')
            {
                scanf("%d%d",&a,&b);
unio(id[a],id[b]);
            }
            else
            {
                scanf("%d",&a);
                id[a]=tn;p[tn]=tn;
                tn++;
            }
        }
        for(i=0;i<n;i++)
        {
        //    printf("id[%d]=%d root=%d\n",i,id[i],find(id[i]));
            int temp=find(id[i]);
            if(!vis[temp]) {
                ans++;
                vis[temp]=1;
            }
        }
        printf("Case #%d: %d\n",cases++,ans);
    }
    return 0;
}
posted @ 2011-10-07 20:15  Because Of You  Views(437)  Comments(0Edit  收藏  举报