poj 3764 The xor-longest Path
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 10128 | Accepted: 2059 |
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
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)
Source
题解:
复习一下字典树,首先我们处理出任意一个点到根的区间亦或和d[x],根据亦或的性质可以知道任意两个点之间的区间亦或和为d[x]^d[y],然后我们要求d[x]^d[y]的最大值。那么就直接字典树,把所有d[x]按二进制数插到字典树中,枚举一个d[x],把他的二进制数插到字典树中,然后在字典树中尽量走相反的就可以了。
代码:
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <cmath> #include <iostream> #define MAXN 100010 #define RG register using namespace std; int dis[MAXN];int tr[MAXN*35][2]; struct edge{ int first; int next; int to; int quan; }a[MAXN*2]; int n,num=0; inline void addedge(int from,int to,int quan){ a[++num].to=to; a[num].quan=quan; a[num].next=a[from].first; a[from].first=num; } inline void dfs1(int now,int f){ for(int i=a[now].first;i;i=a[i].next){ int to=a[i].to,quan=a[i].quan; if(to==f) continue; dis[to]=dis[now]^quan; dfs1(to,now); } } inline void insert(int h){ int now=0; for(RG int i=30;i>=0;i--){ int x=h&(1<<i); if(x) x=1; else x=0; if(!tr[now][x]) tr[now][x]=++num; now=tr[now][x]; } } int ans=0; void dfs(int h){ int now=0,tot=0; for(RG int i=30;i>=0;i--){ int x=(1<<i)&h; if(x) x=0; else x=1; if(tr[now][x]) now=tr[now][x],tot+=1<<i; else now=tr[now][x^1]; } ans=max(ans,tot); } int main() { while(scanf("%d",&n)!=EOF){ num=0; memset(a,0,sizeof(a)); memset(tr,0,sizeof(tr)); memset(dis,0,sizeof(dis));ans=0; for(int i=1;i<n;i++){ int x,y,z; scanf("%d%d%d",&x,&y,&z);x++,y++; addedge(x,y,z); addedge(y,x,z); } num=0; dfs1(1,0); for(int i=1;i<=n;i++){ insert(dis[i]); dfs(dis[i]); } printf("%d\n",ans); } return 0; }