Description
In an edge-weighted tree, the xor-length of a path p is defined as the xor sum of the weights of edges on p:
http://poj.org/problem?id=3764
⊕ is the xor operator.
We say a path the xor-longest path if it has the largest xor-length. Given an edge-weighted tree with n nodes, can you find the xor-longest path?
Input
The input contains several test cases. The first line of each test case contains an integer n(1<=n<=100000), The following n-1 lines each contains three integers u(0 <= u < n),v(0 <= v < n),w(0 <= w < 2^31), which means there is an edge between node u and v of length w.
Output
For each test case output the xor-length of the xor-longest path.
Sample Input
4
0 1 3
1 2 4
1 3 6
Sample Output
7
Hint
The xor-longest path is 0->1->2, which has length 7 (=3 ⊕ 4)
求出D[x]:根节点到x结点路径边权异或和
x->y路径边权异或和为D[x]^D[y]
01Trie,找最大值
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long ll;
const int N=2e5+5,M=30;
int T[N*31][2],tot;
ll End[N];
inline void Insert(ll x){
int p=0,id;
for(int i=M;~i;--i,p=T[p][id])if(!T[p][id=(x>>i)&1])T[p][id]=++tot;
End[p]=x;
}
inline ll Find(ll x){
int p=0,id;
for(int i=M;~i;--i){
id=(x>>i)&1;
if(T[p][id^1])p=T[p][id^1];
else p=T[p][id];
}
return End[p];
}
struct Edge{
int to,next;
ll val;
Edge(){}
Edge(int to,int next,ll val):to(to),next(next),val(val){}
}E[N*3];
int tol,head[N*3];
inline void addedge(int u,int v,ll w){
E[tol]=Edge(v,head[u],w);
head[u]=tol++;
}
int d[N];
void dfs(int u,int f){
for(int i=head[u];~i;i=E[i].next){
int v=E[i].to;
if(v^f)d[v]=d[u]^E[i].val,dfs(v,u);
}
}
int n,u,v;
ll ans,w;
inline void init(){
memset(head,-1,sizeof(head));
memset(T,0,sizeof(T));
ans=tot=tol=0;
}
int main(){
while(~scanf("%d",&n)){
init();
for(int i=1;i<n;++i){
scanf("%d%d%lld",&u,&v,&w);
addedge(u,v,w),addedge(v,u,w);
}
dfs(0,0);
for(int i=0;i<n;++i)Insert(d[i]),ans=max(ans,d[i]^Find(d[i]));
printf("%lld\n",ans);
}
return 0;
}