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 andv 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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
trie树+数论+贪心~
我以为会WA很久的,没想到除了RE的一次就A了……
因为异或两次同样的数等于没有异或,所以一条路上的异或值等于两节点到根节点的值的异或,然后刚开始dfs一遍求出每个点到根节点的异或值,建trie树再贪心就可以了~
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int n,m,x,y,val,fi[100001],ne[200001],w[200001],v[200001],cnt,num[6000001],tr[6000001][2],ans,lin[31];
void add(int u,int vv,int vall)
{
w[++cnt]=vv;ne[cnt]=fi[u];v[cnt]=vall;fi[u]=cnt;
}
void add(int u)
{
int now=0;
for(int i=30;i>=0;i--)
{
int kkz=(u%(1<<(i+1)))/(1<<i);
if(!tr[now][kkz]) tr[now][kkz]=++cnt;
now=tr[now][kkz];
}
}
void dfs(int u,int vv,int vall)
{
int now;
for(int i=fi[u];i;i=ne[i])
if(w[i]!=vv)
{
if(!u) now=v[i];
else now=v[i]^vall;
num[++num[0]]=now;add(now);ans=max(ans,now);
dfs(w[i],u,now);
}
}
int cal(int u)
{
int now=0;
for(int i=30;i>=0;i--)
{
int kkz=(u%(1<<(i+1))/(1<<i))^1;
if(tr[now][kkz]) lin[i]=kkz,now=tr[now][kkz];
else lin[i]=kkz^1,now=tr[now][kkz^1];
}
now=0;
for(int i=30;i>=0;i--) now=now*2+lin[i];
return u^now;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(fi,0,sizeof(fi));num[0]=ans=cnt=0;
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&x,&y,&val);add(x,y,val);add(y,x,val);
}
memset(tr,0,sizeof(tr));
dfs(0,0,0);cnt=0;
for(int i=1;i<=num[0];i++) ans=max(ans,cal(num[i]));
printf("%d\n",ans);
}
return 0;
}