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)
字典树+DFS
求两个结点的异或路径和可以转变:
先用DFS
求所有结点到根节点的异或路径和val[x]
然后任意两点的异或路径和为x - y = val[x] ^ val[y]
因为根据异或性质a ^ a = 0
,x,y
重叠部分答案就是0
,只剩路径的异或和
也就是求两点使他们的异或和最大CH 1602The XOR Largest Pair
用vector<pair<int, int>> E[maxn]
存的话会爆因为是无向图maxn
需要取到200000
#include <vector>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 100010;
int head[2 * maxn], Next[2 * maxn], ver[2 * maxn], edge[2 * maxn];
int tot, ans, trie[maxn * 30][2], val[maxn];
void add(int x, int y, int z)//邻接表存储
{
Next[++tot] = head[x], head[x] = tot;
ver[tot] = y, edge[tot] = z;
}
void dfs(int cur, int temp)//寻找路径
{
if (val[cur] != -1)//别走环路
return;
val[cur] = temp;
for (int i = head[cur]; i; i = Next[i])
dfs(ver[i], temp ^ edge[i]);
}
void insert(int num)//插入
{
int p = 1;
for (int i = 30; ~i; --i)
{
int ch = num >> i & 1;
if (!trie[p][ch])
trie[p][ch] = ++tot;
p = trie[p][ch];
}
}
int check(int num)
{
int p = 1, temp = 0;
for (int i = 30; ~i; --i)
{
int ch = num >> i & 1;
if (trie[p][!ch])//尽量走反
{
temp += 1 << i;
p = trie[p][!ch];
}
else
p = trie[p][ch];
}
return temp;
}
int main()
{
// freopen("1.txt", "r", stdin);
int n;
while (scanf("%d", &n) != EOF)
{
memset(val, -1, sizeof(val));//初始化
memset(trie, 0 ,sizeof(trie));
memset(head, 0 ,sizeof(head));
tot = 0;//别忘记初始化计数
for (int i = 1; i < n; ++i)
{
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
++x, ++y;
add(x, y, z), add(y, x, z);
}
dfs(1, 0); //dfs寻找从x结点到根节点的异或路径和
tot = 1, ans = 0;
for (int i = 1; i <= n; ++i)//求两两最大值
{
ans = max(ans, check(val[i]));
insert(val[i]);
}
printf("%d\n", ans);
}
return 0;
}