【题解】P8511 TEST_68

题目传送门

前言

某场模拟赛的 T4,赛时开题太晚了导致正解没调出来,赛后稍微改改就过了/kk。下面是赛时思路。

分析

异或最大,那肯定是要用一棵 01-Trie 维护。然后我们发现链是好做的,只需要从上到下依次插进 Trie 中,动态维护答案即可。所以我们考虑怎么把一棵树转化为类似链这样好处理的东西。

观察到很多点的答案都是全局最大值,所以我们考虑全局最大值由 \(a_x \oplus a_y\) 得到,显然地,只有 \(x\) 到根路径上的点和 \(y\) 到根路径上的点取不到 \(a_x \oplus a_y\),所以我们单独处理这两条链。

然后我们考虑 从下至上 进行 dfs,每次把链上的点和其他子树中的点插进 Trie 中,实时维护当前最大值。这样每个点最多被插进 Trie 一次,时间复杂度 \(O(n\log a)\)。

代码

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <bits/stdc++.h>
#define ll long long

using namespace std;
const int N = 5e5 + 10, M = 65;
int fa[N];
ll a[N];
vector<int> son[N];
int t[N * M][2], tot;
ll ans[N];
ll now_ans;

inline int read()
{
int x = 0, y = 1; char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') y = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * y;
}

inline void insert(ll x)
{
int p = 0;
for (int i = 63; i >= 0; i--)
{
int c = x >> i & 1;
if (!t[p][c]) t[p][c] = ++tot;
p = t[p][c];
}
}

inline ll query(ll x)
{
ll res = 0;
int p = 0;
for (int i = 63; i >= 0; i--)
{
int c = x >> i & 1;
if (t[p][c ^ 1]) res = res * 2 + 1, p = t[p][c ^ 1];
else res = res * 2, p = t[p][c];
}
if (res > now_ans) now_ans = res;
return res;
}

inline void get(int u)
{
insert(a[u]);
query(a[u]);
for (int i = 0; i < son[u].size(); i++)
{
int v = son[u][i];
get(v);
}
}

inline void dfs(int u, int p)
{
if (u == 0) return;
dfs(fa[u], u);
ans[u] = now_ans;
insert(a[u]);
query(a[u]);
for (int i = 0; i < son[u].size(); i++)
{
int v = son[u][i];
if (v != p) get(v);
}
}

signed main()
{
freopen("d.in", "r", stdin);
freopen("d.out", "w", stdout);
memset(ans, -1, sizeof ans);
int n = read();
for (int i = 2; i <= n; i++)
{
fa[i] = read();
son[fa[i]].push_back(i);
}
for (int i = 1; i <= n; i++)
{
scanf("%lld", &a[i]);
insert(a[i]);
}
ll x = 0, y = 0;
ll res = 0;
for (int i = 1; i <= n; i++)
{
ll now = query(a[i]);
if (now > res)
{
res = now;
x = a[i], y = now ^ a[i];
}
}
int px = 0, py = 0;
for (int i = 1; i <= n; i++)
if (a[i] == x) px = i;
else if (a[i] == y) py = i;
memset(t, 0, sizeof t), tot = 0, now_ans = 0;
dfs(px, 0);
memset(t, 0, sizeof t), tot = 0, now_ans = 0;
dfs(py, 0);
for (int i = 1; i <= n; i++)
printf("%lld\n", ans[i] >= 0 ? ans[i] : res);
return 0;
}