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:
{xor}length§=\oplus{e \in p}w(e)
⊕ 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)
在树上找出一条路径使得这条路径上边权异或值最大。
01字典树那一块是一样的。就是在树上跑的时候,异或的东西不一样。
假如说x->u->v的异或值最大,那么我们在求得时候应该是将lca(x,v)到根节点的异或值给省略掉。所以我们应该在树上跑dfs的时候,应该是不断的用跑过的前缀异或值去求最值的。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#define ll long long
using namespace std;
const int maxx=1e5+100;
struct node{
int trie[2];
int num;
}p[maxx*32];
struct edge{
int v;
int w;
int next;
}e[maxx<<1];
int head[maxx<<1];
int tot,ttot,n,ans;
inline void add(int u,int v,int w)
{
e[tot].v=v,e[tot].w=w,e[tot].next=head[u],head[u]=tot++;
}
inline void init()
{
for(int i=0;i<=ttot;i++)
{
p[i].trie[0]=p[i].trie[1]=0;
p[i].num=0;
}
tot=0;
ttot=0;
memset(head,-1,sizeof(head));
ans=0;
}
inline void Insert(int x)
{
int root=0;
int id;
for(int i=32;i>=0;i--)
{
id=(x>>i)&1;
if(!p[root].trie[id]) p[root].trie[id]=++ttot;
root=p[root].trie[id];
}
p[root].num=x;
}
inline int Find(int x)
{
int root=0;
int id;
for(int i=32;i>=0;i--)
{
id=(x>>i)&1;
if(p[root].trie[id^1]) root=p[root].trie[id^1];
else root=p[root].trie[id];
}
return p[root].num^x;
}
inline void dfs(int u,int f,int c)
{
Insert(c);
for(int i=head[u];i!=-1;i=e[i].next)
{
int to=e[i].v;
if(to==f) continue;
ans=max(ans,Find(c^e[i].w));//类似于求了一个前缀。
dfs(to,u,c^e[i].w);
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
init();
int l,r,w;
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&l,&r,&w);
l++;r++;
add(l,r,w);
add(r,l,w);
}
dfs(1,0,0);
printf("%d\n",ans);
}
return 0;
}
努力加油a啊,(o)/~