题意
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(p)=\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?
给一颗边权树,求出树上最长的异或和路径.
分析
参照jklover的题解。
利用异或的优秀性质,可以处理出节点 1 到每个点的距离 dis ,那么 u 和 v 之间的异或和距离直接就是 dis[u] ^ dis[v] .被重复计算的部分自身异或两次抵消了.
那么将 dis 数组求出后,问题就变为在这个数组中找两个数,使得这对数异或值最大.
使用 Trie 树的经典做法解决即可.
时间复杂度:31倍线性。
代码
POJ用vector会TLE,只能自己写边表。
//#include<bits/stdc++.h>
#include<cstdio>
#include<iostream>
#include<vector>
#include<cstring>
#define rg register
#define il inline
#define co const
template<class T>il T read()
{
rg T data=0,w=1;
rg char ch=getchar();
while(!isdigit(ch))
{
if(ch=='-') w=-1;
ch=getchar();
}
while(isdigit(ch))
{
data=data*10+ch-'0';
ch=getchar();
}
return data*w;
}
template<class T>il T read(rg T&x)
{
return x=read<T>();
}
typedef long long ll;
using namespace std;
co int N=1e5+1,L=N*31;
int tot,root,ch[L][2],bin[31];
void turn(int x)
{
for(int i=0;i<=30;++i,x>>=1)
bin[i]=x&1;
}
int newnode()
{
++tot;
memset(ch[tot],0,sizeof ch[tot]);
return tot;
}
void ins()
{
int u=root;
for(int i=30;i>=0;--i)
{
if(!ch[u][bin[i]])
ch[u][bin[i]]=newnode();
u=ch[u][bin[i]];
}
}
int find()
{
int u=root,res=0;
for(int i=30;i>=0;--i)
{
if(ch[u][bin[i]^1])
res+=(1<<i),u=ch[u][bin[i]^1];
else
u=ch[u][bin[i]];
}
return res;
}
typedef pair<int,int> pii;
struct edge // edit 2: slow vector
{
int to,nx,w;
}e[N*2];
int ecnt,h[N],v[N];
void add(int x,int y,int w)
{
e[++ecnt].to=y,e[ecnt].w=w;
e[ecnt].nx=h[x],h[x]=ecnt;
}
void dfs(int x,int fa,int val)
{
for(int i=h[x];i;i=e[i].nx)
{
int y=e[i].to;
if(y==fa) continue;
dfs(y,x,v[y]=val^e[i].w);
}
}
int main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
int n;
while(scanf("%d",&n)!=EOF) // edit 1: several test cases
{
tot=0,root=newnode();
ecnt=0;
fill(h+1,h+n+1,0);
for(int i=1;i<n;++i)
{
int u=read<int>()+1,v=read<int>()+1,w=read<int>();
add(u,v,w),add(v,u,w);
}
v[1]=0;dfs(1,0,0);
turn(v[1]);ins();
int ans=0;
for(int i=2;i<=n;++i)
{
turn(v[i]);ins();
ans=max(ans,find());
}
printf("%d\n",ans);
}
return 0;
}