Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 4290 | Accepted: 952 |
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)
Source
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=200000+200;
const int maxm=100000*32+200;
int n;
int sz;
int pre[maxn];
struct node
{
int v;
int w;
int next;
}edge[maxn*2];
struct trie
{
int next[2];
void init()
{
memset(next,0,sizeof(next));
}
}trie[maxm];
int val[maxn];
int cnt;
void init()
{
sz=0;
cnt=1;
memset(pre,-1,sizeof(pre));
memset(val,0,sizeof(val));
}
void adde(int u,int v,int w)
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=pre[u];
pre[u]=cnt++;
}
void dfs(int u,int x,int fa)
{
val[u]=x;
for(int i=pre[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(v==fa) continue;
int w=edge[i].w;
dfs(v,x ^ w,u);
}
}
void insert(int x)
{
int u=0,ind;
for(int i=30;i>=0;i--)
{
if(x&(1<<i))
{
ind=1;
}else ind=0;
if(!trie[u].next[ind])
{
trie[u].next[ind]=++sz;
trie[sz].init();
}
u=trie[u].next[ind];
}
}
int com(int x)
{
int u=0,ind,num=0;
for(int i=30;i>=0;i--)
{
if(x&(1<<i)) ind=0;
else ind=1;
if(trie[u].next[ind])
{
num|=(1<<i);
u=trie[u].next[ind];
}
else u=trie[u].next[!ind];
}
return num;
}
int main()
{
// freopen("in.txt","r",stdin);
while(~scanf("%d",&n))
{
int u,v,w;
init();
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&u,&v,&w);
u++;v++;
adde(u,v,w);
adde(v,u,w);
}
trie[0].init();
dfs(1,0,-1);
int ans=-1;
for(int i=1;i<=n;i++)
{
insert(val[i]);
ans=max(ans,com(val[i]));
}
printf("%d\n",ans);
}
}