【bzoj1954】Pku3764 The xor-longest Path Trie树

给定一棵n个点的带权树，求树上最长的异或和路径

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.

For each test case output the xor-length of the xor-longest path.

4
1 2 3
2 3 4
2 4 6

7

Trie树

#include <cstdio>
#include <algorithm>
#define N 100010
using namespace std;
int head[N] , to[N << 1] , len[N << 1] , next[N << 1] , cnt , v[N] , c[N * 30][2] , tot;
void add(int x , int y , int z)
{
to[++cnt] = y , len[cnt] = z , next[cnt] = head[x] , head[x] = cnt;
}
void dfs(int x , int fa)
{
int i;
for(i = head[x] ; i ; i = next[i])
if(to[i] != fa)
v[to[i]] = v[x] ^ len[i] , dfs(to[i] , x);
}
void insert(int x)
{
int i , p = 0;
bool t;
for(i = 1 << 30 ; i ; i >>= 1)
{
t = x & i;
if(!c[p][t]) c[p][t] = ++tot;
p = c[p][t];
}
}
int query(int x)
{
int i , p = 0 , ans = 0;
bool t;
for(i = 1 << 30 ; i ; i >>= 1)
{
t = x & i;
if(c[p][t ^ 1]) ans += i , p = c[p][t ^ 1];
else p = c[p][t];
}
return ans;
}
int main()
{
int n , i , x , y , z , ans = 0;
scanf("%d" , &n);
for(i = 1 ; i < n ; i ++ ) scanf("%d%d%d" , &x , &y , &z) , add(x , y , z) , add(y , x , z);
dfs(1 , 0);
for(i = 1 ; i <= n ; i ++ ) insert(v[i]);
for(i = 1 ; i <= n ; i ++ ) ans = max(ans , query(v[i]));
printf("%d\n" , ans);
return 0;
}


|转载请注明 [原文链接][作者] ，谢谢！

posted @ 2017-06-24 10:13  GXZlegend  阅读(324)  评论(0编辑  收藏  举报