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.
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
题意:M X Y表示把X堆积木放在Y堆积木的上边,C X 表示输出X下边有几堆积木,在整个p输入范围内整体移动。例如在样例中,第二个和第三个C的输出中,整个M操作实现后积木的情况应该是这样的:第一个C 1 中1的下边只有6这堆积木,所以输出为1,而M 2 4代表了把2移到4上边,在把2 4 这个整体移到1 6 上边而M 2 6 表示把2移到6上边之后再整体移到上一个M执行的操作后所得结果的上边。C 3 表示积木3下边有几堆,结果为0,C 4 表示4的下边有几堆,有1 和 6 这两堆,输出为2;
思路:
注意:初始化必须从0开始,从1 开始就出错,不知道为啥。
在这里插入代码片
#include"cstdio"
#include"cstring"
#include"algorithm"
#include"iostream"
using namespace std;
int pre[100005];
int d[100005],r[100005];
void init()
{
for(int i=0;i<=30005;i++)//初始化
{
pre[i]=i;
d[i]=0;//深度
r[i]=1;//到根的距离,i是根节点,初始化以它为根的树共有一个节点
}
}
int find(int x)
{
if(x!=pre[x])//父节点不为自己
{
int t=pre[x];
pre[x]=find(pre[x]);//递归寻找父节点的上一节点
d[x]+=d[t];//加上父亲的
}
return pre[x];
}
int join(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
pre[fx]=fy;
d[fx]+=r[fy];//fx下边多了r[fy]个节点
r[fy]+=r[fx];//以fy为根的树多了r[fx]个节点
}
}
int main()
{
int p;
while(scanf("%d",&p)!=EOF)
{
init();
for(int i=0;i<p;i++)
{
char w;
cin>>w;
int a,b;
if(w=='M')
{
scanf("%d %d",&a,&b);
join(a,b);
}
else
{
scanf("%d",&a);
find(a);
printf("%d\n",d[a]);
}
}
}
return 0;
}