# [Codeforces 893F. Subtree Minimum Query]线段树合并

## 1. 题目链接

[Codeforces 893F. Subtree Minimum Query]

## 3. 解题思路

qwb说这是线段树合并的经典套路题。

## 4. 实现代码

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double lb;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ull, ull> puu;
typedef pair<lb, lb> pbb;
typedef vector<int> vi;

const int inf = 0x3f3f3f3f;
const ll infl = 0x3f3f3f3f3f3f3f3fLL;
template<typename T> inline void umax(T &a, T b) { a = max(a, b); }
template<typename T> inline void umin(T &a, T b) { a = min(a, b); }
template<typename T> inline T randIntv(const T& a, const T& b) { return (T)rand() % (b - a + 1) + a; }
void debug() { cout << endl; }
template<typename T, typename ...R> void debug (T f, R ...r) { cout << "[" << f << "]"; debug (r...); }

const int MAXN = 100005;
int n, m, r;
ll a[MAXN];
struct Edge {
int v, next;
} edge[MAXN << 1];
void ini(int n) {
etot = 0;
for (int i = 0; i <= n; ++i) head[i] = -1;
}
void ins(int u, int v) {
}
#define lch     nd[rt].ch[0]
#define rch     nd[rt].ch[1]
struct TNode {
ll val;
int ch[2];
void ini() { ch[0] = ch[1] = 0; val = infl; }
} nd[MAXN * 50];
int root[MAXN], rsz;

void pushUp(int rt) {
nd[rt].val = min(nd[lch].val, nd[rch].val);
}

void update(int p, ll v, int l, int r, int& rt) {
nd[rt = ++ rsz].ini();
if (l == r) {
nd[rt].val = v;
return;
}
int md = (l + r) >> 1;
if (p <= md) update(p, v, l, md, lch);
else update(p, v, md + 1, r, rch);
pushUp(rt);
}

int merge(int u, int v) {
if (!v) return u;
if (!u) return v;
int ret = ++ rsz; nd[ret].ini();
nd[ret].ch[0] = merge(nd[u].ch[0], nd[v].ch[0]);
nd[ret].ch[1] = merge(nd[u].ch[1], nd[v].ch[1]);
nd[ret].val = min(nd[u].val, nd[v].val);
return ret;
}

void dfs(int u, int fa, int d) {
dep[u] = d;
update(dep[u], a[u], 1, n, root[u]);
for (int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].v;
if (v == fa) continue;
dfs(v, u, d + 1);
root[u] = merge(root[u], root[v]);
}
}

ll query(int L, int R, int l, int r, int rt) {
if (L <= l && r <= R) return nd[rt].val;
int md = (l + r) >> 1; ll ret = infl;
if (L <= md) umin(ret, query(L, R, l, md, nd[rt].ch[0]));
if (R > md) umin(ret, query(L, R, md + 1, r, nd[rt].ch[1]));
return ret;
}

int main() {
#ifdef ___LOCAL_WONZY___
freopen("input.txt", "r", stdin);
#endif // ___LOCAL_WONZY___
int u, v, p, q, x, k;
ll last = 0;
scanf("%d %d", &n, &r);
for (int i = 1; i <= n; ++i) scanf("%lld", &a[i]);
ini(n);
for (int i = 2; i <= n; ++i) {
scanf("%d %d", &u, &v);
ins(u, v), ins(v, u);;
}
rsz = 0;
nd[null = 0].ini();
dfs(r, r, 1);
scanf("%d", &m);
for (int i = 1; i <= m; ++i) {
scanf("%d %d", &p, &q);
x = (p + last) % n + 1, k = (q + last) % n;
last = query(dep[x], dep[x] + k, 1, n, root[x]);
printf("%lld\n", last);
}
#ifdef ___LOCAL_WONZY___
cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC * 1000 << "ms." << endl;
#endif // ___LOCAL_WONZY___
return 0;
}