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
| #include <bits/stdc++.h> #define mp make_pair #define pb push_back #define sz(x) (int)x.size() #define all(x) begin(x), end(x) #define fi first #define se second #define debug(x) cerr << #x << " " << x << '\n' using namespace std; using ll = long long; using pii = pair<int,int>; using pli = pair<ll,int>; const int INF = 0x3f3f3f3f, N = 1e5 + 5; const ll LINF = 1e18 + 5; constexpr int mod = 1e9 + 7; int n, r, a[N], in[N], out[N], dfn, dep[N]; int m, p, q, mxdep; vector<int> G[N]; namespace PSegTree { #define ls(x) t[x].l #define rs(x) t[x].r int rt[N], tot; struct node { int l, r, mn; }t[N<<5]; inline void newnode(int &p) { t[++tot] = t[p]; p = tot; } void upd(int &p, int l, int r, int x, int v) { newnode(p); if(l==r) { t[p].mn = min(t[p].mn, v); return; } int mid = (l+r) >> 1; if(x<=mid) upd(ls(p), l, mid, x, v); else upd(rs(p), mid+1, r, x, v); t[p].mn = min(t[ls(p)].mn, t[rs(p)].mn); } int ask(int p, int l, int r, int ql, int qr) { if(l>=ql&&r<=qr) return t[p].mn; int ans = INF, mid = (l+r)>>1; if(ql<=mid) ans = min(ans, ask(ls(p), l, mid, ql, qr)); if(qr>mid) ans = min(ans, ask(rs(p), mid+1, r, ql, qr)); return ans; } #undef ls #undef rs } using namespace PSegTree; void dfs(int u, int fa) { in[u] = ++dfn; dep[u] = dep[fa] + 1; mxdep = max(mxdep, dep[u]); for(int v : G[u]) { if(v==fa) continue; dfs(v, u); } out[u] = dfn; } void bfs() { queue<int> q; q.push(r); int curd = 0; rt[0] = 0; t[0].mn = INF; while(sz(q)) { int u = q.front(); q.pop(); if(dep[u]>curd) { rt[dep[u]] = rt[curd]; curd = dep[u]; } upd(rt[dep[u]], 1, n, in[u], a[u]); for(int v : G[u]) if(dep[v]==dep[u]+1) q.push(v); } } int main() { scanf("%d%d", &n, &r); for(int i=1; i<=n; i++) scanf("%d", a+i); for(int i=1; i<n; i++) { int x, y; scanf("%d%d", &x, &y); G[x].pb(y); G[y].pb(x); } dfs(r, 0); bfs(); scanf("%d", &m); int lstans = 0; while(m--) { scanf("%d%d", &p, &q); p = (p+lstans)%n + 1; q = (q+lstans)%n; printf("%d\n", lstans=ask(rt[min(mxdep, dep[p]+q)], 1, n, in[p], out[p])); } return 0; }
|