跳到正文

个人记录

[01Trie]带权树最长异或路径

Little_corn约 4 分钟
原文

这是 2026年1月31日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年1月31日
更新
2026年1月31日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

题意描述:

给定一棵 nn 个点的带权树,结点下标从 11 开始到 nn。寻找树中找两个结点,求最长的异或路径。

异或路径指的是指两个结点之间唯一路径上的所有边权的异或值。

1<=n<=1e51<=n<=1e5, 0<=w<=1e90<=w<=1e9

解法:

预处理+ 0-1 trie :

首先将无根树转有根树(这里设根为1).

  • 设 aia_{i} 为根到 ii 节点经过的边权异或值

现在我们欲求 ii 与 jj 节点唯一路径上的所有边权的异或值,可设:

  • x1x_{1} 为从根到 ii 与 jj 的最近公共祖先经过的边权异或值,

  • x2x_{2} 为 ii 到 ii 与 jj 的最近公共祖先经过的边权异或值,

  • x3x_{3} 为 jj 到 ii 与 jj 的最近公共祖先经过的边权异或值.

则 ai=x1xor⁡x2a_{i}=x_{1} \operatorname{xor} x_{2}, aj=x1xor⁡x3a_{j}=x_{1} \operatorname{xor} x_{3}

ii与jj节点唯一路径上的所有边权的异或值为x2xorx3x_{2}xor x_{3}

由 (axor⁡c)xor⁡(bxor⁡c)=axor⁡c(a \operatorname{xor} c)\operatorname{xor}(b \operatorname{xor} c)=a \operatorname{xor} c 可得:

i与 j节点唯一路径上的所有边权的异或值就为aixor⁡aja_{i} \operatorname{xor} a_{j}


这样我们就把问题转化为:

已知nn个数,求最大异或对.

我们可以建立一棵 0-1 trie 树

将每个数的二进制表示存入trie 树中

欲使一个数与另一个数的异或和最大,就应该每位取反(即为0变1,1变0)

注意对细节的处理

代码实现:

C++
#include<bits/stdc++.h>
using namespace std;

const int N=4e6+10,M=2;
int n,a[100001],cnt;
int ans;

struct tr{
	int u,w;
};
vector<tr>tree[N];

struct Trie01{
	int idn=1;
	int f[N][M];
	void insert(int num){
		int p=1;
		for(int i=31;i>=0;i--){
			int o=num>>i&1;
			if(!f[p][o])f[p][o]=++idn;
			p=f[p][o];
		}
	} 
	int search(int num){
		int p=1,res=0;
		for(int i=31;i>=0;i--){
			int o=num>>i&1;
			if(f[p][o^1]){
				res=res*2+(o^1);
				p=f[p][o^1];// o^1 就是 o 取反
			}
			else{
				res=res*2+o;
				p=f[p][o];
			}
		}
		return res;
	}
}trie;

void dfs(int x,int fa,int xr){//深搜预处理出所有异或和
	a[++cnt]=xr;
	for(int i=0;i<tree[x].size();i++){
		if(tree[x][i].u!=fa)dfs(tree[x][i].u,x,xr^tree[x][i].w);
	}
	return;
}

int main(){
	cin>>n;
	for(int i=1;i<n;i++){
		int u,v,w;
		cin>>u>>v>>w;
		tree[u].push_back((tr){v,w});
		tree[v].push_back((tr){u,w});
	}
	dfs(1,0,0);
	for(int i=1;i<=cnt;i++)trie.insert(a[i]);
	for(int i=1;i<=cnt;i++){
		int x=trie.search(a[i]);
		ans=max(ans,x^a[i]);
	}
	cout<<ans<<endl;
	
	return 0;
}