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代表把含有1的石子堆放到含有2的石子堆上面;输入C 就是查询输出 当前石子下有多少石子。
一开始就是想带权并查集就是求得当前结点到根的距离,而直接开数组sum在merge中相加只能求得合并后的堆的石子总数。而且这个总数只存在根节点。
。。两个方法都行不通。。但是很搞笑的是,合起来,这个题就做出来了。
要求的是石子下面有多少颗石子,我本来一直想着从上往下求。怎么也求不到。。但是如果把根节点放在每一个堆的底部,其实每个堆都是单线的,根本没有多线,所以不会出现多个根的情况,所以把根放在底部是完全可行的。
然后因为,两个堆合并只有两种情况,将一个放到一堆上面,这个在merge里面就可以解决,因为,直接合并在根结点上,再用rank[p1]=num[p2]; p1的下面的石子数目就可以确定了,而且find上面由于直接合成的根节点,所以rank也不会改变。
而第二种情况 将一堆放到一个(或者另一堆)上面,由于根节点改变,旧的根节点有了rank[p1]=num[p2],而新的根节点p2一直维持在0上,在旧的堆的子结点在find的时候由于根节点变化了。所以rank得到更新。。。
所以分析得很清楚。。但我自己真的能想得到吗 哭。。。
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=100100;
typedef long long LL;
LL rank1[maxn];
LL num[maxn];
int f[maxn];
void init()
{
for(int i=0;i<=30110;i++)
{
f[i]=i;
rank1[i]=0;
num[i]=1;
}
}
int find(int x)
{
if(x==f[x])
return f[x];
else
{
int t=f[x];
f[x]=find(f[x]);
rank1[x]+=rank1[t];
return f[x];
}
}
int merge(int a,int b)
{
int p1=find(a);
int p2=find(b);
if(p1!=p2)
{
f[p1]=p2;
rank1[p1]=num[p2]; //p2是它的最底部。解决方法 最底部是根
num[p2]+=num[p1];
num[p1]=0;
}
}
int main()
{
int t;
cin>>t;
init();
while(t--)
{
char cmp[3];
cin>>cmp;
if(cmp[0]=='M')
{
int a,b;
cin>>a>>b;
merge(a,b);
}
else
{
int a;
cin>>a;
find(a);
cout<<rank1[a]<<endl;
}
}
}