Luogu P4551 最长异或路径

题目描述

https://www.luogu.com.cn/problem/P4551

Solution

$01Trie$ 板子题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 100010
using namespace std;

int n, m;

struct Edge {
int to, next, w;
} e[maxn * 2]; int c1, head[maxn];
inline void add_edge(int u, int v, int w) {
e[c1].to = v; e[c1].w = w;
e[c1].next = head[u]; head[u] = c1++;
}

int dis[maxn];
void dfs(int u, int fa) {
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w; if (v == fa) continue;
dis[v] = dis[u] ^ w; dfs(v, u);
}
}

const int N = 30;
struct Trie {
int v, ch[2];
} T[maxn * 31]; int rt = 1, top = 1;
void insert(int v) {
int i = rt;
for (int o = N; ~o; --o) {
int d = v >> o & 1;
if (!T[i].ch[d]) T[i].ch[d] = ++top;
i = T[i].ch[d];
}
}

int query(int i, int v, int o) {
if (o == -1) return 0;
int d = v >> o & 1;
if (T[i].ch[d ^ 1]) return (1 << o) + query(T[i].ch[d ^ 1], v, o - 1);
else return query(T[i].ch[d], v, o - 1);
}

int ans;
int main() { memset(head, -1, sizeof head);
ios::sync_with_stdio(false);
cin.tie(nullptr);

cin >> n;
for (int i = 1; i < n; ++i) {
int x, y, z; cin >> x >> y >> z;
add_edge(x, y, z); add_edge(y, x, z);
} dfs(1, 0);
for (int i = 1; i <= n; ++i) insert(dis[i]);
for (int i = 1; i <= n; ++i)
ans = max(ans, query(rt, dis[i], N));
cout << ans << "\n";
return 0;
}