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
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)
大致题意:给你一颗带权树,让你找出一条路径,使得该路径上的边的异或和最大。
思路:假设从根节o点出发,ao表示节点a到根节点o的路径的异或和,bo表示节点b到根节点o的路径的异或和,那么节点a到节点b的路径的异或和即为ao^bo。所以我们可以从根节点出发,dfs遍历一遍所有的节点,然后将他们路径的异或和建立一颗01字典树,然后再去这颗树中查询当前对应的值的异或的最大值,取最大即可。
代码如下
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define LL long long
#define ULL unsigned long long
const int MAXN=100005;
int ch[MAXN*32][2];
int a[MAXN];//存储从根节点出发的第i条路径
int wei;//从根节点出发的路径的编号
int root=1,tot=1;
void add(int x)
{
int p=root;
for(int i=31;i>=0;i--)
{
int k=(x>>i)&1;
if(!ch[p][k]) ch[p][k]=++tot;
p=ch[p][k];
}
}
int query(int x)
{
int ans=0;
int p=root;
for(int i=31;i>=0;i--)
{
int k=(x>>i)&1;
if(ch[p][k^1])
ans^=(1<<i),p=ch[p][k^1];
else
p=ch[p][k];
}
return ans;
}
int tol;
int head[MAXN];//head[i]存储当前以i点为起点的边的编号
int vis[MAXN];
struct Edge
{
int to,cost;// edge[i].to表示编号为i的边所连接下个点 ,edge[i].cost表示编号为i的边 的权值
int next;//edge[i].next表示与编号为i的边同起点的上一条边的编号
}edge[2*MAXN];
void addedge(int u,int v,int w)
{
edge[tol].to=v;
edge[tol].cost=w;
edge[tol].next=head[u];
head[u]=tol++;
}
void dfs(int u,int v)
{
for(int i=head[u];i!=-1;i=edge[i].next)
{
int to=edge[i].to;
if(!vis[to])
{
vis[to]=1;
a[wei++]=v^edge[i].cost;
add(v^edge[i].cost);
dfs(to,v^edge[i].cost);
}
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
memset(ch,0,sizeof(ch));
tot=1;
tol=0;
wei=0;
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
int x,y,z;
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&x,&y,&z);
addedge(x,y,z);
addedge(y,x,z);
}
add(0);
vis[0]=1;
dfs(0,0);
int ans=0;
for(int i=0;i<n-1;i++)
ans=max(ans,query(a[i]));
printf("%d\n",ans);
}
return 0;
}