#include <stdio.h>
int father[30011],deep[30011],h[30011];//数组H[i]表示i下有多少个方块 ,deep[i]表示i所在栈堆的高度
int find(int x)
{
if(x!=father[x])
{
int t=father[x];
father[x]=find(father[x]);
h[x]+=h[t];
}
return father[x];
}
void join(int x, int y)
{
x=find(x);
y=find(y);
if(x!=y)
{
father[x]=y;
h[x]=deep[y];
deep[y]+=deep[x];
deep[x]=0;
}
}
int main()
{
int n,a,b,p;
char op[2];
scanf("%d",&n);
for(int i=1;i<30001;i++)
{
father[i]=i;
deep[i]=1;
h[i]=0;
}
for(int i=1;i<=n;i++)
{
scanf("%s",op);
if(op[0]=='M')
{
scanf("%d%d",&a,&b);
join(a,b);
}
else {
scanf("%d",&p);
int k=find(p);
printf("%d\n",h[p]);
}
}
return 0;
}
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.
Input
* Line 1: A single integer, P
* Lines 2..P+1: Each of these lines describes a legal operation. Line 2 describes the first operation, etc. Each line begins with a 'M' for a move operation or a 'C' for a count operation. For move operations, the line also contains two integers: X and Y.For count operations, the line also contains a single integer: X.
Note that the value for N does not appear in the input file. No move operation will request a move a stack onto itself.
Output
Print the output from each of the count operations in the same order as the input file.
Sample Input
6 M 1 6 C 1 M 2 4 M 2 6 C 3 C 4
Sample Output
1 0 2
此处属于复制:
给定N个方块,排成一行,将它们编号1到N。再给出P个操作:
①M i j表示将i所在的那一堆移到j所在那一堆的顶上。
②C i表示一个询问,询问i下面有多少个方块。
•你需要写一个程序来完成这些操作。
我们设f[i]是每个方块所在位置的最底下方块的编 号,h[i]是每个方块之下有多少个方块(开始赋成0)。每次读入合并操作Y和X时:
首先找到X和Y的父亲(最底下的点),同时更新:f[fy]=fx。但是很快问题就来了——我们怎么更新f[fy]的高度呢?我们不能获知左边堆里最上面一层的h[i]!
咨询了RZZ后,我又开了个数组deep[i],表示i所在的堆内的高度(仅当i是底层的方格)。初始化时是1。进行如图的操作时,h[fy]=deep[fx],同时deep[fx]+=deep[fy]。
有人可能要问:右侧堆中底层的元素已经转移了,那么它上面的点呢?这里,要用到类似于线段树里的lazy-tag思想,即询问时再更新值。如果询问右侧某一点,我们只需在它寻找父亲、路径压缩时,再增加一个修改h的操作即可。