Cube Stacking
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 28711 | Accepted: 10081 | |
Case Time Limit: 1000MS |
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
问题描述:有n个相同的立方体(从1开始编号),开始有n堆(每堆一个),有P次操作,每次有两种选择,操作一M X Y,将包含立方体X的一堆移动包含立方体Y的一堆的上面,操作二C X,查询立方体X下面的立方体的个数。对于每个查询操作,输出相应的答案。
解题思路:带权并查集,让每堆中各个立方体都以最顶上的立方体为祖先结点,设结点 i 的祖先结点为 j ,cnt[i] 表示结点 i 到 j之间的立方体数,sum[j]表示以结点 j 为祖先结点的立方体数,则C i 的结果为 sum[j] - cnt[i]
AC的C++代码:
#include<iostream>
using namespace std;
const int N=30010;
int pre[N],cnt[N],sum[N];//pre存储结点i的父节点,cnt存储结点i到父结点之间的立方体数,sum存储以结点i为祖先结点的立方体数
void init()
{
for(int i=0;i<N;i++){
pre[i]=i;//初始化每个结点的父结点为自己
cnt[i]=0;//自己到自己之间只有0个
sum[i]=1;//本身只有一个
}
}
int find(int x)
{
if(x!=pre[x]){
int r=pre[x];
pre[x]=find(r);
cnt[x]+=cnt[r];//原来x的父结点为r,x到r之间的立方体数为cnt[x]。现在x的父结点为pre[x],x到pre[x]之间的立方体数为cnt[i]+=cnt[r]
}
return pre[x];
}
//将x这一堆移动到y这一堆的顶上
void join(int x,int y)
{
int fx=find(x);//x一堆的顶上立方体为fx
int fy=find(y);//y一堆的顶上立方体为fy
if(fx!=fy){
pre[fy]=fx;//由于是x这一堆移动到y这一堆上,因此fy的父节点为fx
cnt[fy]=sum[fx];//fy到父节点fx之间的立方体数=原来x这一堆的立方体数 (即sum[fx])
sum[fx]+=sum[fy];//如今以fx为根结点的立方体数是两堆立方体数之和
}
}
int main()
{
int p;
init();
scanf("%d",&p);
while(p--){
char c;
int x,y;
scanf(" %c",&c);
if(c=='M'){
scanf("%d%d",&x,&y);
join(x,y);
}
else if(c=='C'){
scanf("%d",&x);
int r=find(x);
printf("%d\n",sum[r]-cnt[x]-1);
}
}
return 0;
}