【AcWing 238. 银河英雄传说】带权并查集

题目链接

题意:

现在有两种操作,第一种是 M x y ,表示将第 x 个战舰所在列的全部战舰整体地挪到第 y 个战舰所在列后面,第二种是 C x y ,询问第 x 个战舰和 第 y 个战舰的距离是多少。

分析:

这个题很容易就能想到并查集,在合并区间的时候需要一个size属性记录每个集合的元素的数量,其他都是带权并查集的板子,具体看代码吧:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<cstdlib>
#include<climits>
#include<unordered_map>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef unsigned long long ull;
const int mod = 1e9+7;
const int N = 30010;
int pa[N],deep[N],siz[N];
int find(int x){
	if(x != pa[x]){
//		int t = find(pa[x]);
//		deep[x] += deep[pa[x]];
//		pa[x] = t;	
		int t=pa[x];
		pa[x]=find(pa[x]);
		deep[x]+=deep[t];
	}
	return pa[x];
}
int main(){
	int T;
	scanf("%d",&T);
	for(int i=0;i<N;i++) deep[i] = 0, siz[i] = 1,pa[i] = i;
	while(T--){
		char op[2];
		int x,y;
		scanf("%s%d%d",op,&x,&y);
		int a = find(x),b = find(y);
		if(op[0] == 'M'){
			if(a == b) continue;
			pa[a] = b;
			deep[a] = siz[b];
			siz[b] += siz[a];
		}
		else{
			if(a != b) cout<<-1<<endl;
			else cout<<max(0,abs(deep[x]-deep[y])-1)<<endl;
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇智波一打七~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值