Problem Description
John are playing with blocks. There are N blocks (1 <= N <= 30000) numbered 1...N。Initially, there are N piles, and each pile contains one block. Then John do some operations P times (1 <= P <= 1000000). There are two kinds of operation:
M X Y : Put the whole pile containing block X up to the pile containing Y. If X and Y are in the same pile, just ignore this command.
C X : Count the number of blocks under block X
You are request to find out the output for each C operation.
M X Y : Put the whole pile containing block X up to the pile containing Y. If X and Y are in the same pile, just ignore this command.
C X : Count the number of blocks under block X
You are request to find out the output for each C operation.
Input
The first line contains integer P. Then P lines follow, each of which contain an operation describe above.
Output
Output the count for each C operations in one line.
Sample Input
6 M 1 6 C 1 M 2 4 M 2 6 C 3 C 4
Sample Output
1 0 2
本题题目的意思是:Farmer John 和 Betsy 在玩一种游戏:堆箱子。其中有两种操作:一种是移动,由字母‘M’表示;另一种是输出,由字母‘C’表示。
即:
1、M X Y 是表示:把含X 的那一叠箱子按照原来的顺序全部堆到含y 的那一叠箱子的最上面;
2、C X 是表示:计算含X 的箱子下面有几个箱子,并输出。
这些箱子是一条直线的往上叠。
思路:找到含X的那叠箱子的箱子总是减去X上面的箱子数再减去一就是所要的答案。
明白几点:如果a堆在b上,那么b上面的箱子数就是等于含a的那叠箱子的总数;
b那叠箱子总数就为a的总数加上原来b的箱子总数。
还要注意在路径压缩的时候对num_up数组的更新:
num_up[x]+=num_up[tmp];//该节点x头上的节点个数等于其父节点头上的加上自己原本头上的
这里用递归:可以这样理解:把x点头上的每个点相加
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int num[330000];
int set[330000];
int under[330000];
int find(int x)
{
int tmp;
if (x!=set[x])
{
tmp = find(set[x]);
under[x] += under[set[x]];
set[x] = tmp;
}
return set[x];
}
void merge(int a,int b)
{
int fx=find(a);
int fy=find(b);
if(fx!=fy)
{
under[fx]=num[fy];
num[fy]+=num[fx];
set[fx]=fy;
}
}
int main()
{
int n,a,b;
char s[5];
while(scanf("%d",&n)!=EOF)
{
memset(under,0,sizeof(under));
for(int i=0; i<=n; i++)//初始化
{
set[i]=i;
num[i]=1;
}
for(int i=0; i<n; i++)
{
cin>>s;
if(s[0]=='M')
{
cin>>a>>b;
merge(a,b);
}
else
{
cin>>a;
find(a);
printf("%d\n",under[a]);
}
}
}
return 0;
}