【POJ 3764】The xor-longest Path 中文题意&题解&代码(C++)

The xor-longest Path

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

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)


中文题意:
给出n个结点,n-1条边,每条边附有一个权值. 定义:两结点间的异或长度为两点之间所有边权值相异或得到的值.求:这个图中的最长异或长度.


题解:
首先我们需要知道异或的两个性质
A xor B = B xor A , A xor B xor B = A xor 0 = A
其次我们发现这是一个有n个点,n-1条边的连通图,即是一棵树,那么任意两点间的路径就一定只有一条。
这样的话我们很容易会想到一个O(n^2)的做法,那就是首先以任意一个节点作为根节点(为了方便我们取0节点为根节点)写一个DFS遍历整棵树,就能求出每个点到根节点的路径的异或长度记为 val [ i ] ,那么利用上述异或的第二个性质就能理解,任意两点(如x,y)间的路径的异或长度 L(x,y) = val [ x ] xor val [ y ](不理解的画个图自己试一试就知

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值