Luogu P2633 Count on a tree

题目描述

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

Solution

跟序列上做法类似,只需要在 $dfs$ 的时候建树即可

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
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define maxn 100010
using namespace std;

int n, m, a[maxn];

int b[maxn], cnt;
void init_hash() {
for (int i = 1; i <= n; ++i) b[i] = a[i];
sort(b + 1, b + n + 1); cnt = unique(b + 1, b + n + 1) - b - 1;
for (int i = 1; i <= n; ++i) a[i] = lower_bound(b + 1, b + cnt + 1, a[i]) - b;
}

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

#define lc T[i].ch[0]
#define rc T[i].ch[1]
#define Lc T[j].ch[0]
#define Rc T[j].ch[1]
struct zhuxi {
int v, ch[2];
} T[maxn * 20]; int top, rt[maxn];
void update(int &i, int j, int l, int r, int k, int v) {
i = ++top; T[i] = T[j]; T[i].v += v;
if (l == r) return ; int m = l + r >> 1;
if (k <= m) update(lc, Lc, l, m, k, v);
else update(rc, Rc, m + 1, r, k, v);
}

int p, fp;
int query(int i, int j, int l, int r, int k) {
int v = T[Lc].v + T[lc].v - T[T[p].ch[0]].v - T[T[fp].ch[0]].v;
if (l == r) return l; int m = l + r >> 1;
if (k <= v) return p = T[p].ch[0], fp = T[fp].ch[0], query(lc, Lc, l, m, k);
else return p = T[p].ch[1], fp = T[fp].ch[1], query(rc, Rc, m + 1, r, k - v);
}

int dep[maxn], f[maxn][21];
void dfs(int u, int fa) {
update(rt[u], rt[fa], 1, cnt, a[u], 1);
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa) continue;
dep[v] = dep[u] + 1; f[v][0] = u; dfs(v, u);
}
}

void init_lca() {
for (int j = 1; j <= 20; ++j)
for (int i = 1; i <= n; ++i) f[i][j] = f[f[i][j - 1]][j - 1];
}

int get_lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
for (int i = 20; ~i; --i)
if (dep[f[x][i]] >= dep[y]) x = f[x][i];
if (x == y) return x;
for (int i = 20; ~i; --i)
if (f[x][i] ^ f[y][i]) x = f[x][i], y = f[y][i];
return f[x][0];
}

int lans;
int main() { memset(head, -1, sizeof head);
cin >> n >> m;
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
init_hash();
for (int i = 1; i < n; ++i) {
int x, y; scanf("%d%d", &x, &y);
add_edge(x, y); add_edge(y, x);
} dep[1] = 1; dfs(1, 0); init_lca();
for (int i = 1; i <= m; ++i) {
int x, y, z; scanf("%d%d%d", &x, &y, &z); x ^= lans;
p = get_lca(x, y); fp = f[p][0]; p = rt[p]; fp = rt[fp];
printf("%d\n", lans = b[query(rt[x], rt[y], 1, cnt, z)]);
}
return 0;
}