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
题目说明:给定一个N个节点的数,树上每条边都有1个权值。从树中选择两个点x和y,把从x到y的路径上的所有的边权XOR(异或)起来,求最大的结果。
做法:比较模板的一道字典树题,设D[x]表示根到x上所有边权的XOR值,那么x到y的XOR值显然为D[x]xor D[y]。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #define rep(i,a,b) for(int i=a;i<=b;i++) 5 #define fx(i,x) for(int i=ls[x];i;i=e[i].next) 6 #define N 100009 7 #define LL long long 8 #define fill(a,b) memset(a,b,sizeof(a)) 9 using namespace std; 10 int ls[N],n,tot,t[N*60][2],cnt,ans; 11 int d[N]; 12 struct edge{ 13 int to,next,w; 14 }e[N*2]; 15 16 inline int max(int a,int b) {return a>b?a:b;} 17 18 inline void Add(int x,int y,int z){ 19 e[++tot].to=y; 20 e[tot].next=ls[x]; 21 e[tot].w=z; 22 ls[x]=tot; 23 } 24 25 inline int Read(){ 26 int s=0; 27 char ch=getchar(); 28 for(;ch<'0'||ch>'9';ch=getchar()); 29 for(;ch>='0'&&ch<='9';s=(s<<3)+(s<<1)+(ch^48),ch=getchar()); 30 return s; 31 } 32 33 void Init(){ 34 fill(d,0); 35 fill(ls,0); 36 fill(t,0); 37 fill(e,0); 38 tot=0; 39 ans=0; 40 cnt=0; 41 rep(i,1,n-1){ 42 int u,v,w; 43 u=Read(),v=Read(),w=Read(); 44 Add(u,v,w),Add(v,u,w); 45 } 46 47 } 48 49 inline void Dfs(int x,int fa){ 50 fx(i,x){ 51 if (e[i].to==fa) continue; 52 d[e[i].to]=d[x]^e[i].w; 53 Dfs(e[i].to,x); 54 } 55 } 56 57 inline void Insert(int x){ 58 int root=0,ch; 59 for(int i=30;i>=0;i--){ 60 if (x&(1<<i)) ch=1; else ch=0; 61 if (!t[root][ch]) t[root][ch]=++cnt; 62 root=t[root][ch]; 63 } 64 } 65 66 inline int Search(int x){ 67 int root=0,sum=0,ch; 68 for(int i=30;i>=0;i--){ 69 if(x&(1<<i)) ch=0; else ch=1; 70 if(t[root][ch]){ 71 sum|=(1<<i); 72 root=t[root][ch]; 73 }else root=t[root][!ch]; 74 } 75 return sum; 76 } 77 78 void Work(){ 79 rep(i,0,n) Insert(d[i]); 80 rep(i,0,n) ans=max(ans,Search(d[i])); 81 } 82 83 int main(){ 84 while(~scanf("%d",&n)){ 85 Init(); 86 Dfs(1,n+2); 87 Work(); 88 printf("%d\n",ans); 89 } 90 }