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
| #include <bits/stdc++.h> #define LOG 20 #define MAX_N 100000 #define mid ((s+t)>>1) using namespace std; template <class T> inline void read(T &x) { x = 0; int c = getchar(), f = 1; for (; !isdigit(c); c = getchar()) if (c == 45) f = -1; for (; isdigit(c); c = getchar()) (x *= 10) += f*(c-'0'); } int n, m, q, cnt; int rt[MAX_N+5], fa[MAX_N+5][LOG+1], dep[MAX_N+5]; int a[MAX_N+5], b[MAX_N+5], h[MAX_N+5], rk[MAX_N+5]; vector <int> G[MAX_N+5]; struct node {int ls, rs, c;} tr[MAX_N*35+5]; bool cmp (const int &x, const int &y) {return a[x] < a[y];} void addedge(int u, int v) {G[u].push_back(v), G[v].push_back(u);} void DFS(int u) { for (int i = 1; i <= LOG; i++) if (dep[u] >= (1<<i)) fa[u][i] = fa[fa[u][i-1]][i-1]; for (int i = 0, v; i < (int)G[u].size(); i++) if ((v = G[u][i]) ^ fa[u][0]) fa[v][0] = u, dep[v] = dep[u]+1, DFS(v); } int LCA(int a, int b) { if (dep[a] < dep[b]) swap(a, b); for (int i = LOG; ~i; i--) if (dep[a]-(1<<i) >= dep[b]) a = fa[a][i]; if (a == b) return a; for (int i = LOG; ~i; i--) if (fa[a][i]^fa[b][i]) a = fa[a][i], b = fa[b][i]; return fa[a][0]; } void modify(int v, int o, int s, int t, int x) { tr[v] = tr[o]; if (s == t) {tr[v].c++; return;} if (x <= mid) modify(tr[v].ls = ++cnt, tr[o].ls, s, mid, x); else modify(tr[v].rs = ++cnt, tr[o].rs, mid+1, t, x); tr[v].c = tr[tr[v].ls].c+tr[tr[v].rs].c; } int query(int v1, int v2, int v3, int v4, int s, int t, int k) { if (s == t) return s; int lsz = tr[tr[v1].ls].c+tr[tr[v2].ls].c-tr[tr[v3].ls].c-tr[tr[v4].ls].c; if (k <= lsz) return query(tr[v1].ls, tr[v2].ls, tr[v3].ls, tr[v4].ls, s, mid, k); return query(tr[v1].rs, tr[v2].rs, tr[v3].rs, tr[v4].rs, mid+1, t, k-lsz); } void build(int u) { modify(rt[u] = ++cnt, rt[fa[u][0]], 1, m, b[u]); for (int i = 0, v; i < (int)G[u].size(); i++) if ((v = G[u][i]) ^ fa[u][0]) build(v); } int main() { read(n), read(q); for (int i = 1; i <= n; i++) read(a[i]), rk[i] = i; for (int i = 1, u, v; i < n; i++) read(u), read(v), addedge(u, v); sort(rk+1, rk+n+1, cmp); for (int i = 1; i <= n; b[rk[i++]] = m) if (i == 1 || (a[rk[i]]^a[rk[i-1]])) h[++m] = a[rk[i]]; DFS(1), build(1); int lst = 0; while (q--) { int u, v, k; read(u), read(v), read(k), u ^= lst; int anc = LCA(u, v); printf("%d\n", lst = h[query(rt[u], rt[v], rt[anc], rt[fa[anc][0]], 1, m, k)]); } return 0; }
|