思路
这道题首先思考如何求树上的异或路径。
暴力会超时 O ( n 2 ) O(n^2) O(n2) ,所以想想怎么优化。
设一个 a [ i ] a[i] a[i] 表示点 i i i 到根节点的异或路径,那么我们可以从根节点开始暴力搜树,
在搜的过程中不断求异或,然后就可以 O ( n ) O(n) O(n) 预处理出 a [ i ] a[i] a[i]。
之后问题就转化成了求 s [ i ] s[i] s[i] 异或 s [ j ] s[j] s[j] 的最大值,和 例2最大异或和 一样。
代码
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int a[1000010],trie[1000010][2],zdtot=1,v[1000010];
int tot,hd[1000010];
int n,x,y,w,ans;
struct node
{
int y,next,z;
}b[1000010];
void add(int x,int y,int w)
{
b[++tot].y=y;
b[tot].z=w;
b[tot].next=hd[x];
hd[x]=tot;
}
void dfs(int x,int fa)
{
for(int i=hd[x]; i; i=b[i].next)
{
int yy=b[i].y;
if(yy==fa)
continue;
a[yy]=a[x]^b[i].z;
dfs(yy,x);
}
}
void insert(int w)
{
int dg=1;
for(int i=31; i>=0; i--)
{
int cc=(a[w]>>i)&1;
if(!trie[dg][cc])
trie[dg][cc]=++zdtot;
dg=trie[dg][cc];
}
v[dg]++;
}
int sfind(int w)
{
int dg=1,maxn=0,cc;
for(int i=31; i>=0; i--)
{
if(((a[w]>>i)&1)==1)
cc=0;
else
cc=1;
if(trie[dg][cc])
maxn+=(1<<i);
else
cc=(a[w]>>i)&1;
dg=trie[dg][cc];
}
return maxn;
}
int main()
{
cin>>n;
for(int i=1; i<=n-1; i++)
{
scanf("%d%d%d",&x,&y,&w);
add(x,y,w);
add(y,x,w);
}
a[1]=0;
dfs(1,0);
for(int i=1; i<=n; i++)
insert(i);
for(int i=1; i<=n; i++)
ans=max(ans,sfind(i));
cout<<ans;
return 0;
}