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.
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
Source
USACO 2004 U S Open
并查集扩展,确实很巧妙啊,想了很久才明白的
对于这题,我们需要一个额外的数组记录每个点的高度,我们在执行合并的操作的时候,要先把根节点的高度更新,这个是很容易的,只需要加上所要并到的那个集合的元素个数就行。关键在于如何修改某个非根节点的点的高度,这就要求在递归查询祖先的时候动点手脚了
比如已经有合并 F[1]=2,F[2]=3,F[3]=4,求1的高度,那么实际过程是第一堆放到第二堆,第二堆放到第三堆,第三堆放到第四堆
int find(int x)
{
if(father[x]==-1)
return x;
int temp=father[x];//记录下父亲节点
father[x]=find(father[x]);//递归寻找最终祖先,在上述例子里就是4
cnt[x]+=cnt[temp];//回溯上来以后,先加上集合4的,再加上集合3的,再加上集合2的,执行完毕后答案
return father[x];
}
其中的temp,分别记录了2,3,4,最后相加过程是4-1,3-1,2-1,虽然可以有很多步的合并,但是我们通过递归可以一步步的分解,最后得到答案
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int father[30010];
int rank[30010];
int cnt[30010];
void init()
{
memset(father,-1,sizeof(father));
memset(cnt,0,sizeof(cnt));
for(int i=0;i<=30010;i++)
rank[i]=1;
}
int find(int x)
{
if(father[x]==-1)
return x;
int temp=father[x];
father[x]=find(father[x]);
cnt[x]+=cnt[temp];
return father[x];
}
void merge(int x,int y)
{
int a=find(x);
int b=find(y);
if(a!=b)
{
cnt[a]+=rank[b];
rank[b]+=rank[a];
father[a]=b;
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
int x,y;
init();
char op[4];
for(int i=1;i<=n;i++)
{
scanf("%s",op);
if(op[0]=='M')
{
scanf("%d%d",&x,&y);
merge(x,y);
}
else
{
scanf("%d",&x);
find(x);//这一步不能少,可能有新的merge操作,没有及时的find的话,就会有错误了
printf("%d\n",cnt[x]);
}
}
}
return 0;
}