首页 > 代码库 > POJ1988 Cube Stacking (!hard)

POJ1988 Cube Stacking (!hard)

 Description
Farmer John and Betsy are playing a game with N (1 <= N <= 30,000)identical cubes labeled 1 through N. They start with N stacks, each containing a single cube. Farmer John asks Betsy to perform P (1<= P <= 100,000) operation. There are two types of operations:
moves and counts.
* In a move operation, Farmer John asks Bessie to move the stack containing cube X on top of the stack containing cube Y.
* In a count operation, Farmer John asks Bessie to count the number of cubes on the stack with cube X that are under the cube X and report that value.

Write a program that can verify the results of the game. 


题目大意:(同银河舰队传说) 对于n块积木,进行两种操作:M a b 把a移到b上,C a 询问a下面有几块积木。

思路:用并查集和tot,sum数组维护,像银河一样简单AC。。。

code:
#include<iostream>
#include<cstdio>
using namespace std;
int fa[30001]={0},sum[30001]={0},len[30001]={0};
int rool(int x)
{
int j;
if (fa[x]!=x)
{
j=rool(fa[x]);
len[x]=len[x]+len[fa[x]];
fa[x]=j;
}
return fa[x];
}
int main()
{
int p,n,i,j,r1,r2,x,y;
char ch;
scanf("%d",&p);
n=30000;
for (i=1;i<=n;++i)
{
  fa[i]=i;
  sum[i]=1;
    }
    for (i=1;i<=p;++i)
    {
     scanf("%*c%c",&ch);
     if (ch==‘M‘)
     {
     scanf("%d%d",&x,&y);
     r1=rool(x);
     r2=rool(y);
     if (r1!=r2)
     {
     len[r1]=len[r1]+sum[r2];
sum[r2]=sum[r2]+sum[r1];
fa[r1]=r2;
     }
     }
     else
     {
     scanf("%d",&x);
     r1=rool(x);
     printf("%d\n",len[x]);
     }
    }

 

POJ1988 Cube Stacking (!hard)