方塊遊戲(cubes)
阿新 • • 發佈:2018-12-17
【一句話題意】這題和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;
}