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:
⊕ 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
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)
//
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=3010000;
//找异或值最大的两个数
int n;//0~n-1
int a[maxn];
struct Node
{
int flag;
Node* next[2];
};
Node temp[maxn];
int tp;
Node *root;
void reset(Node* p)
{
p->flag=0;
for(int i=0;i<2;i++) p->next[i]=NULL;
}
void init()
{
tp=0;
root=&temp[tp++];
reset(root);
}
void insert(char* word)
{
Node* p=root;
for(int i=0;word[i];i++)
{
int x=word[i]-'0';
if(p->next[x]==NULL)
{
p->next[x]=&temp[tp++];
reset(p->next[x]);
}
p=p->next[x];
}
p->flag=1;
}
int solve(int v)
{
Node* p=root;
int cnt=0;
for(int i=30;i>=0;i--)
{
int x;
if(v&(1<<i)) x=1;
else x=0;
if(p->next[!x]) p=p->next[!x],cnt|=(1<<i);
else p=p->next[x];
}
return cnt;
}
char str[100];
int findMaxXor()
{
init();
for(int i=0;i<n;i++)
{
int k=a[i];
for(int j=30;j>=0;j--,k>>=1) str[j]=(k&1)+'0';
str[31]='\0';
insert(str);
}
int ans=0;
for(int i=0;i<n;i++) ans=max(ans,solve(a[i]));
return ans;
}
//.......类似LCA
struct edge
{
int v,w;
int next;
};
int V,E;
int p[maxn];
edge G[maxn];
int l;
void init0()
{
memset(p,-1,sizeof(p));
l=0;
}
void addedge(int u,int v,int w,int l)
{
G[l].v=v;
G[l].w=w;
G[l].next=p[u];
p[u]=l;
}
void dfs(int u,int fath,int val)
{
a[u]=val;
for(int i=p[u];i!=-1;i=G[i].next)
{
int t=G[i].v,w=G[i].w;
if(t==fath) continue;
dfs(t,u,val^w);
}
}
int main()
{
while(scanf("%d",&V)==1)
{
init0();
for(int i=0;i<V-1;i++)
{
int u,v,w;scanf("%d%d%d",&u,&v,&w);
addedge(u,v,w,l++);
addedge(v,u,w,l++);
}
dfs(0,-1,0);
n=V;
cout<<findMaxXor()<<endl;
}
return 0;
}