poj 3764 The xor-longest Path (01 Trie)

时间:2023-03-09 07:56:54
poj  3764  The xor-longest Path  (01 Trie)

链接:http://poj.org/problem?id=3764

题面:

The xor-longest Path
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:

poj  3764  The xor-longest Path  (01 Trie)

⊕ 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

Hint

The xor-longest path is 0->1->2, which has length 7 (=3 ⊕ 4)

思路;

树上dfs一遍跟区间差不多的写法

实现代码;

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define ll long long
const int M = 4e5+;
int tot;
int ch[*M][],cnt,head[M];
int val[*M],a[M],pre[M],nex[M],dp[M],ans; struct node{
int to,next;
ll w;
}e[M*]; 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 = ; ans = ; cnt = ;
ch[][] = ch[][] = ;
memset(head,,sizeof(head));
} void ins(ll x){
int u = ;
for(int i = ;i >= ;i --){
int v = (x>>i)&;
if(!ch[u][v]){
ch[tot][] = ch[tot][] = ;
val[tot] = ;
ch[u][v] = tot++;
}
u = ch[u][v];
}
val[u] = x;
} int query(int x){
int u = ;
for(int i = ;i >= ;i --){
int v = (x>>i)&;
if(ch[u][v^]) u = ch[u][v^];
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 = ;i < n;i++){
scanf("%d%d%d",&u,&v,&w);
add(u,v,w); add(v,u,w);
}
dfs(,-,);
printf("%d\n",ans);
}
}