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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| #include <cstdio> #include <algorithm> #include <vector> using namespace std; const int N = 1e5 + 10, M = 2e5 + 10; int n, m, len, w[N], p[N], d[N], sz[N], rt[N]; int idx, hd[N], nxt[M], edg[M]; int stmp, son[N], dfn[N], top[N]; struct Node { int l, r, s; } tr[2000010]; int _idx; void pushup(int x) { tr[x].s = tr[tr[x].l].s + tr[tr[x].r].s; } void modify(int &x, int l, int r, int t) { tr[++_idx] = tr[x]; x = _idx; if (l == r) { tr[x].s++; return; } int mid = l + r >> 1; if (t <= mid) modify(tr[x].l, l, mid, t); else modify(tr[x].r, mid + 1, r, t); pushup(x); } int query(int x1, int x2, int y1, int y2, int l, int r, int k) { if (l == r) return l; int t = tr[tr[x1].l].s + tr[tr[x2].l].s - tr[tr[y1].l].s - tr[tr[y2].l].s; int mid = l + r >> 1; if (t >= k) return query(tr[x1].l, tr[x2].l, tr[y1].l, tr[y2].l, l, mid, k); return query(tr[x1].r, tr[x2].r, tr[y1].r, tr[y2].r, mid + 1, r, k - t); } void dfs1(int x) { sz[x] = 1; son[x] = -1; for (int i = hd[x]; ~i; i = nxt[i]) { if (d[edg[i]]) continue; d[edg[i]] = d[x] + 1; p[edg[i]] = x; dfs1(edg[i]); sz[x] += sz[edg[i]]; if (son[x] == -1 || sz[edg[i]] > sz[son[x]]) son[x] = edg[i]; } } void dfs2(int x, int t) { dfn[x] = ++stmp; top[x] = t; if (~son[x]) dfs2(son[x], t); for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != son[x] && edg[i] != p[x]) dfs2(edg[i], edg[i]); } int LCA(int x, int y) { while (top[x] != top[y]) { if (d[top[x]] < d[top[y]]) swap(x, y); x = p[top[x]]; } if (d[x] > d[y]) swap(x, y); return x; } void dfs(int x) { rt[x] = rt[p[x]]; modify(rt[x], 1, len, w[x]); for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != p[x]) dfs(edg[i]); } void add(int a, int b) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) hd[i] = -1; vector<int> ws; for (int i = 1; i <= n; i++) { scanf("%d", &w[i]); ws.push_back(w[i]); } sort(ws.begin(), ws.end()); len = ws.erase(unique(ws.begin(), ws.end()), ws.end()) - ws.begin(); for (int i = 1; i <= n; i++) w[i] = lower_bound(ws.begin(), ws.end(), w[i]) - ws.begin() + 1; for (int i = 1, u, v; i < n; i++) { scanf("%d%d", &u, &v); add(u, v); add(v, u); } d[1] = 1; dfs1(1); dfs2(1, 1); dfs(1); for (int u, v, k, last = 0; m; m--) { scanf("%d%d%d", &u, &v, &k); u ^= last; int lca = LCA(u, v); printf("%d\n", last = ws[query(rt[u], rt[v], rt[lca], rt[p[lca]], 1, len, k) - 1]); } return 0; }
|