【一句话题意】这题和luogu【银河英雄传说】很像(以下提及的“方块”和“舰队”的意义相当),只是c询问的是舰队x以下的舰队数。
【分析】一道经典的带权并查集,考场中虽然YY了出来,但也有了不少的学习。这道题的任意一个方块如果没有堆其他立方柱到当前立方柱,那么当中的方块到最高的方块距离是不会变的;如果堆了其他立方柱则所有方块的到最高点的距离都自然增加len(立方柱)。很明显:孩子到爷爷的距离==孩子到父亲的距离+父亲到爷爷的距离。每次并查集路径压缩更新f数组的同时,更新每个点到父亲的差值。转移立方柱时,我们立方柱顶点的高度也可以O(1)更新。
【code】
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=3e4+1000;
int p,x,y,n=3e4;
char op,tmp[10];
int f[maxn],h[maxn],height[maxn];
inline void read(int &x){
x=0;char tmp=getchar();
while(tmp<'0'||tmp>'9') tmp=getchar();
while(tmp>='0'&&tmp<='9') x=(x<<1)+(x<<3)+tmp-'0',tmp=getchar();
}
int find(int x){
int d;
if(f[x]!=x){
d=find(f[x]);
if(d!=f[x]) h[x]+=h[f[x]];
f[x]=d;
}
return f[x];
}
int main(){
freopen("cubes.in","r",stdin);
freopen("cubes.out","w",stdout);
cin>>p;gets(tmp);
for(int i=1;i<=n;i++)
f[i]=i,height[i]=1,h[i]=0;
for(int i=1;i<=p;i++){
op=getchar();
if(op=='M'){
scanf("%d%d",&x,&y);
h[find(y)]=height[find(x)];
height[find(x)]+=height[find(y)];
f[find(y)]=find(x);
}
else{
scanf("%d",&x);
printf("%d\n",height[find(x)]-h[x]-1);
}
gets(tmp);
}
return 0;
}