最长异或路径
题目
解析
考虑推一下两个点之间的距离式子:
d
x
,
y
=
d
x
,
L
C
A
(
x
,
y
)
x
o
r
d
L
C
A
(
x
,
y
)
,
y
d_{x,y}=d_{x,LCA(x,y)}\;xor\;d_{LCA(x,y),y}
dx,y=dx,LCA(x,y)xordLCA(x,y),y
再异或上两个
d
1
,
L
C
A
(
x
,
y
)
d_{1,LCA(x,y)}
d1,LCA(x,y)得
d
x
,
y
=
d
1
,
x
x
o
r
d
1
,
y
d_{x,y}=d_{1,x}\;xor\;d_{1,y}
dx,y=d1,xxord1,y
于是直接DFS求出距离,再采用trie就可以AC了
code:
#include<cstring>
#include<cstdio>
#define rr register int
using namespace std;
struct trie
{
int ch[3000010][26],bo[3000010],tot=1;
inline void insert(int s){int p=1;for(rr i=31;i>=0;--i)p=(ch[p][(s>>i)&1])?(ch[p][(s>>i)&1]):(ch[p][(s>>i)&1]=++tot);}
inline int ask(int s)
{
int p=1,ans=0,q;
for(rr i=31;i>=0;--i){q=((s>>i)&1);if(ch[p][!q])p=ch[p][!q],ans+=(1<<i);else p=ch[p][q];}
return ans;
}
}AC;
int n,a[100010],head[100010],to[200010],nxt[200010],w[200010],tot,x,y,z;
inline void add(int x,int y,int z){to[++tot]=y,w[tot]=z,nxt[tot]=head[x],head[x]=tot;}
inline void dfs(int x,int fa){for(rr i=head[x];i;i=nxt[i])if(to[i]!=fa)a[to[i]]=w[i]^a[x],dfs(to[i],x);}
int main()
{
scanf("%d",&n);
for(rr i=1;i<n;++i)scanf("%d%d%d",&x,&y,&z),add(x,y,z),add(y,x,z);
dfs(1,0);
for(rr i=1;i<=n;++i)AC.insert(a[i]);
for(rr i=1;i<=n;++i)a[i]=AC.ask(a[i]),a[0]=(a[0]<a[i])?a[i]:a[0];
printf("%d",a[0]);
return 0;
}