poj 3764 The xor-longest Path

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:

_{xor}length(p)=\oplus_{e \in p}w(e)

⊕ 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)

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;
}

 

转载于:https://www.cnblogs.com/renjianshige/p/9890259.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值