AcWing 144. 最长异或值路径
原题链接
中等
作者:
wjie
,
2020-07-08 21:51:10
,
所有人可见
,
阅读 622
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 1e5 + 5;
int head[N], arr[N], cnt;
int trie[N*31][2], idx;
struct Edge{
int v;
int w;
int next;
}edge[N << 1];
void add(int u, int v, int w)
{
edge[++cnt].v = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt;
}
void dfs(int u, int father)
{
for (int i = head[u]; i; i = edge[i].next)
{
int v = edge[i].v;
if (v == father)
continue;
arr[v] = arr[u] ^ edge[i].w;
dfs(v, u);
}
}
void insert(int x)
{
int p = 0;
for (int i = 30; i >= 0; --i)
{
int bit = (x >> i) & 1;
int &s = trie[p][bit];
if (!s)
s = ++idx;
p = s;
}
}
int query(int x)
{
int p = 0, res = 0;
for (int i = 30; i >= 0; --i)
{
int bit = (x >> i) & 1;
res <<= 1;
if (trie[p][bit^1])
{
res |= 1;
p = trie[p][bit^1];
}
else
p = trie[p][bit];
}
return res;
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
add(u, v, w);
add(v, u, w);
}
int root = 0;
dfs(root, -1);
// for (int i = 0; i < n; ++i)
// printf("%d ", arr[i]);
for (int i = 0; i < n; ++i)
insert(arr[i]);
int maxv = 0;
for (int i = 0; i < n; ++i)
maxv = max(maxv, query(arr[i]));
printf("%d", maxv);
return 0;
}