链接:http://poj.org/problem?id=3764
题面:
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 11802 | Accepted: 2321 |
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
40 1 31 2 41 3 6
Sample Output
7
Hint
The xor-longest path is 0->1->2, which has length 7 (=3 ⊕ 4)
思路;
树上dfs一遍跟区间差不多的写法
实现代码;
#include#include #include using namespace std;#define ll long longconst int M = 4e5+10;int tot;int ch[32*M][2],cnt,head[M];int val[32*M],a[M],pre[M],nex[M],dp[M],ans;struct node{ int to,next; ll w;}e[M*2];void add(int u,int v,int w){ e[++cnt].to = v;e[cnt].w = w;e[cnt].next = head[u];head[u] = cnt;}void init(){ tot = 1; ans = 0; cnt = 0; ch[0][0] = ch[0][1] = 0; memset(head,0,sizeof(head));}void ins(ll x){ int u = 0; for(int i = 31;i >= 0;i --){ int v = (x>>i)&1; if(!ch[u][v]){ ch[tot][0] = ch[tot][1] = 0; val[tot] = 0; ch[u][v] = tot++; } u = ch[u][v]; } val[u] = x;}int query(int x){ int u = 0; for(int i = 31;i >= 0;i --){ int v = (x>>i)&1; if(ch[u][v^1]) u = ch[u][v^1]; else u = ch[u][v]; } return x^val[u];}void dfs(int u,int fa,int val){ ins(val); for(int i = head[u];i;i = e[i].next){ int v = e[i].to; if(v == fa) continue; ans = max(ans,query(val^e[i].w)); dfs(v,u,val^e[i].w); }}int main(){ int n,u,v,w; while(scanf("%d",&n)!=EOF){ init(); for(int i = 1;i < n;i++){ scanf("%d%d%d",&u,&v,&w); add(u,v,w); add(v,u,w); } dfs(0,-1,0); printf("%d\n",ans); }}