题目描述

 给定一棵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树

由于x^x=0,所以树上x和y之间路径的异或和 = x到根路径的异或和 xor y到根路径的异或和。

所以我们先对整棵树进行dfs,求出每个节点到根的路径异或和dis,并加入到Trie树。

然后枚举树上的节点,在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;
}

最新文章

  1. Firemonkey 移动平台 Form 显示使用 ShowModal 范例
  2. win8, VS2013 .NET 4.5在哪找svcutil.exe?
  3. QQ分组实现,可收缩---ExpandableListView
  4. 注解方式传LIST@RequestBody
  5. [LeetCode] 55. Jump Game 解题思路
  6. JS如何得到Repeater中TextBox控件的值
  7. c语言字符串比较函数strcmp
  8. linux:C语言通过ICMP协议判断局域网内部主机是否存活
  9. TimesTen数据库表中显示中文乱码的真正原因
  10. 爬虫-通过本地IP地址从中国天气网爬取当前城市天气情况
  11. Saiku控制页面展示的数据过长自动换行(二十四)
  12. MySQL高级知识(十三)——表锁
  13. 关于Mac或Linux下GO的Permission denied提示错误
  14. Python全栈之路----流程控制+循环
  15. Unity&amp;Sqlite数据库
  16. &quot;//./root/CIMV2&quot; because of error 0x80041003. Events cannot be delivered through this filter until the problem is corrected.
  17. CSS中的三种常用定位
  18. 批量分割视频opencv
  19. 利用telnet模拟http请求
  20. 5 数据结构、栈、队列、链表、list、dict、迷宫问题

热门文章

  1. 2017.10.4 QBXT 模拟赛
  2. hdu 3861 The King’s Problem
  3. python爬虫之路——初识lxml库和xpath语法
  4. JavaScript对象属性
  5. SAP OData编程指南
  6. C++中malloc / free 和 new / delete 的区别?
  7. javaweb基础(13)_session防止表单重复提交
  8. java基础—多态(动态加载)
  9. MVCPager学习小记
  10. 01_5_Struts_ActionMethod_DMI_动态方法调用