pku 1988 Cube Stacking(和银河英雄类似)

#include <stdio.h>

#define MAXN 30005

int father[MAXN],before[MAXN],count[MAXN];

int find(int x)
{
    if(father[x]<0) return x;
    int f=find( father[x] );
    before[x] += before[ father[x] ];
    return father[x] = f;
}
void merge(int x,int y)
{
    int fx,fy;
    fx = find(x);
    fy = find(y);
    father[fy] = fx;
    before[fy] += count[fx];
    count[fx] += count[fy];
}

int main()
{
    int n,i,j;
    char ch;
    while(scanf("%d",&n)!=EOF)
    {
        getchar();
        for(i=1; i<MAXN; i++)
        {
            father[i]=-1;
            before[i]=0;
            count[i]=1;
        }
        while(n--)
        {
            scanf("%c",&ch);
            if(ch=='M')
            {
                scanf("%d %d",&i,&j);
                merge(i,j);
            }
            else
            {
                scanf("%d",&i);
                int fi=find(i);
                printf("%d\n",count[fi] - before[i] - 1);
            }
            getchar();
        }
    }
    return 0;
}

 

posted @ 2010-08-24 21:40  菜到不得鸟  阅读(95)  评论(0)    收藏  举报