您的位置:首页 > 其它

POJ 3764 The xor-longest Path (01字典树 + DFS)

2015-11-14 19:11 459 查看
[align=center]The xor-longest Path[/align]

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 4946 Accepted: 1076
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)

题目链接:http://poj.org/problem?id=3764

题目大意:一棵树,每条边有一个权值,求任意两点路径上异或和的最大值

题目分析:点数很小,先DFS求起点(随便设个点)到其它各点的路径异或和,因为a^c = (a^b) ^ (b^c),设b = lca(a,c),因此再把每个点插入01字典树,贪心选异或值最大的两个
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int const MAX = 2e6 + 5;
int xval[MAX], head[MAX];
int n, cnt, ans;

struct EDGE
{
int to, w;
int next;
}e[MAX];

struct Tire
{
int root, tot, next[MAX][2], end[MAX];

inline int Newnode()
{
memset(next[tot], -1, sizeof(next[tot]));
end[tot] = 0;
return tot ++;
}

inline void Init()
{
tot = 0;
root = Newnode();
}

inline void Insert(int x)
{
int p = root;
for(int i = 31; i >= 0; i--)
{
int idx = ((1 << i) & x) ? 1 : 0;
if(next[p][idx] == -1)
next[p][idx] = Newnode();
p = next[p][idx];
}
end[p] = x;
}

inline int Search(int x)
{
int p = root;
for(int i = 31; i >= 0; i--)
{
int idx = ((1 << i) & x) ? 1 : 0;
if(idx == 0)
p = (next[p][1] != -1) ? next[p][1] : next[p][0];
else
p = (next[p][0] != -1) ? next[p][0] : next[p][1];
}
return x ^ end[p];
}

}tr;

void Init()
{
cnt = 0;
memset(head, -1, sizeof(head));
memset(xval, 0, sizeof(xval));
}

void Add(int u, int v, int w)
{
e[cnt].to = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt ++;
}

void DFS(int u, int fa)
{
for(int i = head[u]; i != -1; i = e[i].next)
{
int v = e[i].to;
if(v != fa)
{
xval[v] = xval[u] ^ e[i].w;
DFS(v, u);
}
}
return;
}

int main()
{
while(scanf("%d", &n) != EOF)
{
Init();
int u, v, w, st;
ans = 0;
tr.Init();
for(int i = 0; i < n - 1; i++)
{
scanf("%d %d %d", &u, &v, &w);
Add(u, v, w);
Add(v, u, w);
st = u;
}
DFS(st, -1);
for(int i = 0; i < n; i++)
{
tr.Insert(xval[i]);
ans = max(ans, tr.Search(xval[i]));
}
printf("%d\n", ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: