跳到正文

个人记录

《Xor-MST》 解题报告

daduoli约 3 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

又做不出来。。。

我们看到 MSTMST ,考虑最小生成树,看到异或,可以考虑 trietrie

然后我们如果考虑最小生成树,那么实际上我们每次要先从权值最小的边开始连,也就是说我们从二进制中的最低位开始连边,然后到高位。

那么一开始全部权值为 11 的边都已连上,接着看权值为 22 的,但是如果要连权值为 2−32-3 的,但是因为我们连完了权值为 11 的,所以现在我们有了若干个联通块,他们内部不能连边,所以只能将连通块合并,考虑联通块两两合并,也就是说两个连通块中得有一条边相连。

那么我们考虑用 trietrie 枚举其中最小的一条边。如果有左儿子同时存在或右儿子同时存在,那么考虑先走这个,否则再走异边,但是权值要加上 (1<<dep)(1<<dep) ,最后求一个最小值即可。

时间复杂度 O(nlogsizelogn)O(nlogsizelogn)

每个深度,我们会把整棵树跑一遍,有 lognlogn 个深度。

这其实类似于 BoruvkaBoruvka ,但是只是用了 BoruvkaBoruvka 的思想,而没有使用它的代码,巧妙的是对于 BoruvkaBoruvka 中,对于每个联通块找最小边的操作,只需要对于当前层数的兄弟里查找即可,且一定在兄弟中。

tricktrick :完全图的 MSTMST 考虑 BoruvkaBoruvka

C++
#include<bits/stdc++.h>
typedef long long LL;

using namespace std;
const int NN=6e6+10,MAXN=2e5+10;
const LL inf=(LL)1e18;
int n,cnt;
int ch[NN][2],tot;
int a[MAXN];
void insert(int ii,int x) {
	int u=0;
	for(int i=30;i>=0;--i) {
		bool to;
		if((x&(1<<i))) to=1;
		else to=0;
		if(!ch[u][to]) ch[u][to]=++tot;
		u=ch[u][to];
	}
}
LL find(int x,int y,int dep) {
	if(dep==-1) return 0;
	LL res=inf;
	if(ch[x][0]&&ch[y][0]) {
		res=find(ch[x][0],ch[y][0],dep-1);
	}
	if(ch[x][1]&&ch[y][1]) {
		res=min(res,find(ch[x][1],ch[y][1],dep-1));
	}
	if(res!=inf) return res;
	if(ch[x][0]&&ch[y][1]) res=min(res,find(ch[x][0],ch[y][1],dep-1));
	if(ch[x][1]&&ch[y][0]) res=min(res,find(ch[x][1],ch[y][0],dep-1));
	return res+(1<<dep);
}
LL dfs(int node,int dep) {
	LL res=0;
	if(dep<0) return 0;
	if(ch[node][0]&&ch[node][1]) {
		res=dfs(ch[node][0],dep-1);
		res+=dfs(ch[node][1],dep-1);
		res+=find(ch[node][0],ch[node][1],dep-1)+(1<<dep);
		return res;
	}
	if(ch[node][0]&&!ch[node][1]) return dfs(ch[node][0],dep-1);
	return dfs(ch[node][1],dep-1);
}
int main () {
	scanf("%d",&n);
	for(int i=1;i<=n;++i) {
		scanf("%d",&a[i]);
		insert(i,a[i]);
	}
	cout<<dfs(0,30);
	return 0;
}
原文