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时,要输入两个数,并把包含前一个数的树整体放在包含后一个数的树上,求树中某个数下方有几个数。
样例演示:
AC代码:
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<map>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
int pre[30005];
int d[30005];//记录树上每个点的深度
int r[30005];//记录树的高度(根节点的高度)
void make()
{
for(int i=0;i<30005;i++)
{
pre[i]=i;
d[i]=0;//深度为0
r[i]=1;//初始为1(本身)
}
}
int find(int i)
{
int fx;
if(pre[i]==i)
{
return i;
}
fx=pre[i];//记录更新前指向的位置(压缩路径后返回的值是根节点,提前记录::本人不熟悉递归,被坑一次)
pre[i]=find(fx);//压缩路径
d[i]+=d[fx];//递归依次更新树上每个点的深度
return pre[i];//压缩路径
}
void unite(int i,int j)
{
int x=find(i);
int y=find(j);
if(y==x)
{
return ;
}
pre[x]=y;//合并两棵树
d[x]=r[y];//更新树的深度
r[y]+=r[x];//更新树的高度
return ;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
make();
for(int i=0;i<n;i++)
{
char ss;
cin>>ss;
if(ss=='M')
{
int x,y;
scanf("%d %d",&x,&y);
unite(x,y);
}
else
{
int x;
scanf("%d",&x);
find(x);//调用find()把含x树更新一遍
printf("%d\n",d[x]);
}
}
}
return 0;
}