代码如下
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 5e5 + 10;
struct Edge{
int to;
int next;
int weight;
}edge[MAXN << 1];
int head[MAXN << 1],cnt = 0,d[MAXN << 1];
int n;
void init(){
for(int i = 0;i < MAXN * 2;i++){
edge[i].next = -1;
head[i] = -1;
edge[i].weight = 0;
d[i] = 0;
}
cnt = 0;
}
void addedge(int u,int v,int w){
edge[cnt].to = v;
edge[cnt].weight = w;
edge[cnt].next = head[u];
head[u] = cnt++;
}
void dfs(int x,int father){
for(int i = head[x];i != -1;i = edge[i].next){
if(edge[i].to != father){
if(x != 1){
d[edge[i].to] = d[x] ^ edge[i].weight;
}else{
d[edge[i].to] = edge[i].weight;
}
dfs(edge[i].to,x);
}
}
}
int trie[MAXN << 2][2],cntt = 1;
void insert(int a){
int p = 1;
for(int i = 30;i >= 0;i--){
int ch = ((a >> i) & 1);
if(trie[p][ch] != 0){
trie[p][ch] = ++cntt;
}
p = trie[p][ch];
}
}
int find(int a){
int p = 1,ans = 0;
for(int i = 30;i >= 0;i--)
{
int ch = !((a >> i) & 1);
if(trie[p][ch] != 0){
if(trie[p][!ch]) p = trie[p][!ch];
else return ans;
}else p = trie[p][ch], ans += (1 << i);
}
return ans;
}
int main(){
cin >> n;
init();
for(int i = 1;i < n;i++){
int u,v,w;
cin >> u >> v >> w;
addedge(u,v,w);
addedge(v,u,w);
}
dfs(1,0);
for(int i = 1;i <= n;i++){
insert(d[i]);
}
int ans = 0;
for(int i=1;i<=n;++i){
int t = find(d[i]);
if(t>ans) ans=t;
}
cout << ans;
return 0;
}
字典树部分是照着题解写的,但是输出结果总是2147483647。。