3376: [Usaco2004 Open]Cube Stacking 方块游戏
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 256 Solved: 141
[ Submit][ Status][ Discuss]
Description
约翰和贝茜在玩一个方块游戏.编号为1到n的n(1≤n≤30000)个方块正放在地上.每个构成一个立方柱.
游戏开始后,约翰会给贝茜发出P(1≤P≤100000)个指令.指令有两种:
1.移动(M):将包含X的立方柱移动到包含Y的立方柱上.
2.统计(C):统计名含X的立方柱中,在X下方的方块数目.
写个程序帮贝茜完成游戏.
Input
第1行输入P,之后P行每行输入一条指令.形式为“M X Y”或者“C X”
输入保证不会有将立方柱放在自己头上的指令.
Output
每一行,对于每个统计指令,输出其结果.
Sample Input
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4
Sample Output
1
0
2
将x方块放在y上相当于合并root[x]和root[y],val[x]表示x到fa[x]中间有多少块
bet[x]表示x所在那一立方柱有多高
#include<stdio.h>
#include<algorithm>
using namespace std;
int fa[130005], val[130005], bet[130005];
int Find(int x)
{
int temp;
if(fa[x]==0)
return x;
temp = Find(fa[x]);
val[x] += val[fa[x]];
return fa[x] = temp;
}
int main(void)
{
char ch;
int n, i, x, y, t1, t2;
scanf("%d", &n);
for(i=1;i<=n;i++)
bet[i] = 1;
for(i=1;i<=n;i++)
{
scanf(" %c", &ch);
if(ch=='M')
{
scanf("%d%d", &x, &y);
t1 = Find(x);
t2 = Find(y);
if(t1!=t2)
{
fa[t1] = t2;
val[t1] = bet[t2];
bet[t2] += bet[t1];
}
}
else
{
scanf("%d", &x);
Find(x);
printf("%d\n", val[x]);
}
}
return 0;
}