POJ3764 The xor-longest Path
来源:互联网 发布:linux 10秒后关机 编辑:程序博客网 时间:2024/05/14 22:09
题意:给定一颗n(1 <= n <= 100000)树,求一条路径,使得路径上的边权异或和最大。
分析:
我本人是比较讨厌异或类型的题的...
异或有一个恒等式:x ^ y = (x ^ z) ^ (y ^ z).
那么我们根据这个等式,可以将原题转化一下,首先创建一个源点(这道题我直接用的0),计算每个点到源点的长度,然后原题转化为从这n个点中寻找两个数,使得它们的异或值最大。
如何计算长度呢?
规定每条边是从序号小的点连向序号大的点,初始0的长度是0,然后遍历所有边,按照from的顺序遍历,因为这样from的长度已经算出来,这样就是求一个值使得from的长度异或这个值等于这条边的边权(网上好多说用dfs的,但我搜索渣...).
接下来就是重点,从n个数中选两个异或最大,O(n^2)的暴搜肯定超时,我们考虑用Trie树来实现。
Trie树从高位到低位建树,然后枚举每个点,每位都尝试走到跟当前位不同的点,也就是一个贪心的思想...
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 100005;int n, x, y, z, e, sz, ans, hd[N], nxt[N], to[N], w[N], num[N], ch[3100005][2];void add(int x, int y, int z) {to[++e] = y, w[e] = z, nxt[e] = hd[x], hd[x] = e;}void insrt(int x) {int u = 0;for(int i = 30; i >= 0; i--) {int c = (x >> i) & 1;if(!ch[u][c]) ch[u][c] = ++sz;u = ch[u][c];}}int qry(int x) {int u = 0, v = 0, sum = 0;for(int i = 30; i >= 0; i--) {int c = (x >> i) & 1, _c = c ? 0 : 1;if(ch[v][_c]) v = ch[v][_c], sum = sum * 2 + 1;else v = ch[v][c], sum *= 2;u = ch[u][c];}return sum;}int main() {while(~scanf("%d", &n)) {ans = e = sz = 0;memset(hd, 0, sizeof hd);memset(num, 0, sizeof num);memset(ch, 0, sizeof ch);for(int i = 1; i < n; i++) scanf("%d%d%d", &x, &y, &z), add(min(x, y), max(x, y), z);for(int i = 0; i < n; i++)for(int j = hd[i]; j; j = nxt[j])for(int k = 0; k < 31; k++)if((((num[i] >> k) & 1) ^ 1) == ((w[j] >> k) & 1))num[to[j]] ^= 1 << k;for(int i = 0; i < n; i++) insrt(num[i]);for(int i = 0; i < n; i++) ans = max(ans, qry(num[i]));printf("%d\n", ans);}return 0;}
2 0
- POJ3764:The xor-longest Path
- POJ3764 The xor-longest Path
- poj3764 The xor-longest Path
- 【poj3764】 The xor-longest Path
- poj3764 The xor-longest Path
- POJ3764 The xor-longest Path(字典树)
- trie-bzoj1954-poj3764-The xor-longest Path
- 【POJ3764】The xor-longest Path Trie树+异或性质
- poj3764 The xor-longest Path 字典树与异或
- poj3764 The xor-longest Path(01字典树+dfs)
- The xor-longest Path
- The xor-longest Path POJ
- POJ 3764 The xor-longest Path
- POJ 3764 The xor-longest Path
- POJ 3764 The xor-longest Path
- POJ 3764 The xor-longest Path
- poj 3764 The xor-longest Path
- poj-3764 The xor-longest Path
- 我的 Mac 清单
- red5源码分析---3
- [疯狂Java]I/O:字节流、字符流
- hdu4405(概率dp)
- STL string
- POJ3764 The xor-longest Path
- 区域生长(用鼠标选择一个点进行生长)
- Xcode7 IOS 项目协作开发遇到apple push notification 提示开发者权限enrolled需求提示
- 用c实现HASH表创建、插入、查找、删除、打印(欢迎高手指点)【转】
- nyoj 448 寻找最大数
- UIBarButtonSystemItem 样式 和 图片
- javascript 前端验证 file 上传图片 尺寸 大小
- MTK8321 GPS无法校准
- 为啥要用kmp算法,有什么依据嘛