poj3764 The XOR Longest Path【dfs】【Trie树】

时间:2021-06-17 13:48:37
The xor-longest Path
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 10038   Accepted: 2040

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:

poj3764 The XOR Longest Path【dfs】【Trie树】

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

题意:

给一棵带边权的树,想找得到两个点,他们的路径上的权值异或最小。

思路:

首先我们任意找一个作为根,可以用dfs求出其他节点到根的路径的异或,记为xordis

那么对于树上的任意两个节点i, j,i到j的路径的异或和应该是xordis[i] ^ xordis[j]

因为i到j的路径,相当于i到根,根到j,其中重叠的部分,他们的异或值正好是0

因此这道题就变成了找两点异或值最小,https://www.cnblogs.com/wyboooo/p/9824293.html 和这道题就差不多了

最后还需要注意,search找到的最大值是除根以外的,还需要和xordis比较一下,取较大值。

 #include <iostream>
#include <set>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
typedef long long LL;
#define inf 0x7f7f7f7f int n;
const int maxn = 1e5 + ;
struct edge{
int v, w;
int nxt;
}e[maxn * ];
int head[maxn], tot = ;
int xordis[maxn];
int trie[maxn * + ][], treetot = ; void addedge(int u, int v, int w)
{
e[tot].v = v;
e[tot].w = w;
e[tot].nxt = head[u];
head[u] = tot++;
e[tot].v = u;
e[tot].w = w;
e[tot].nxt = head[v];
head[v] = tot++;
} void dfs(int rt, int fa)
{
for(int i = head[rt]; i != -; i = e[i].nxt){
int v = e[i].v;
if(v == fa)continue;
xordis[v] = xordis[rt] ^ e[i].w;
dfs(v, rt);
}
} void init()
{
memset(head, -, sizeof(head));
tot = ;
memset(xordis, , sizeof(xordis));
memset(trie, , sizeof(trie));
} void insertt(int x)
{
int p = ;
for(int i = ; i >= ; i--){
int ch = x >> i & ;
if(trie[p][ch] == ){
trie[p][ch] = ++tot;
}
p = trie[p][ch];
}
} int searchh(int x)
{
int p = , ans = ;
for(int i = ; i >= ; i--){
int ch = x >> i & ;
if(trie[p][ch ^ ]){
p = trie[p][ch ^ ];
ans |= << i;
}
else{
p = trie[p][ch];
}
}
return ans;
} int main()
{
while(scanf("%d", &n) != EOF){
init();
for(int i = ; i < n - ; i++){
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
addedge(u, v, w);
}
dfs(, -); /*for(int i = 0; i < n; i++){
printf("%d\n", xordis[i]);
}*/ int ans = ;
for(int i = ; i < n; i++){
insertt(xordis[i]);
//cout<<searchh(xordis[i])<<endl;
ans = max(ans, searchh(xordis[i]));
ans = max(ans, xordis[i]);
}
printf("%d\n", ans);
}
return ;
}