跳到正文

题解

P1196 银河英雄传说 题解

Splay_trees约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

0x00 写在前面

这一题基于带有“秩”的并查集进行了一个简单的扩展域操作。

仍然是由相对关系,相减得到绝对关系。

0x01 分析

显然可以维护每一个战舰在自己一列中的编号,用类似于前缀和的思想求距离。

那么当长为 xx 的一列战舰拼接到长为 yy 的一列战舰后时,显然每一艘战舰的编号要加上 yy ,也就是这一列的秩。

所以我们要维护三个量:节点编号,秩,父亲(大雾

还是假设我们已经 find(fa[x]) 了。

那么我们的编号 tag[x] 要加上一个 Δtag\Delta tag ,所以 tag[x]+=tag[fa[x]]。

同样地,我们也要一路更新节点的秩都加上根节点的秩,那么 ord[x]+=ord[tmp] 。

C++
int find(int x)
{
	if(fa[x]==x) return x;
	int tmp=find(fa[x]);
	tag[x]+=tag[fa[x]];
	ord[x]=ord[tmp];
	return fa[x]=tmp;
}

合并的时候,还是只需要切换 ord 和 tag 即可。

0x02 代码

C++
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
int T,fa[30005],ord[30005],tag[30005];
char opt;

int find(int x)
{
	if(fa[x]==x) return x;
	int tmp=find(fa[x]);
	tag[x]+=tag[fa[x]];
	ord[x]=ord[tmp];
	return fa[x]=tmp;
}

int main()
{
	cin>>T;
	for(int i=1; i<=30000; i++)
		fa[i]=i,ord[i]=1;
	while(T--)
	{
		int a,b;
		cin>>opt>>a>>b;
		int p=find(a),q=find(b);
		if(opt=='M')
		{
			if(p!=q)
			{
				fa[p]=q;
				tag[p]=ord[q];
				ord[p]=ord[q]=ord[p]+ord[q];
			}
		}
		else
		{
			if(p!=q)
				cout<<-1<<endl;
			else
				cout<<abs(tag[b]-tag[a])-1<<endl;
		}
	}
	return 0;
}
原文