方块游戏(cubes)

【一句话题意】这题和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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值