在子树内和距离不超过k是一个二维限制,容易想到主席树,但主席树显然没法查最小值,因为不满足区间可减。kdtree和二维线段树可以干这事,但肯定会T飞。但事实上我们的问题有一个特殊性:对某个点x,查询其子树中的depth[x]~depth[x]+y和0~depth[x]+y这两种深度区间实际上是相同的,因为显然x是其子树中最深的节点,0~depth[x]-1这段其实并没有点。于是直接上主席树,外层为深度内层为dfs序,就行了。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define N 100010
#define inf 1000000010
char getc(){char c=getchar();while ((c<'A'||c>'Z')&&(c<'a'||c>'z')&&(c<''||c>'')) c=getchar();return c;}
int gcd(int n,int m){return m==?n:gcd(m,n%m);}
int read()
{
int x=,f=;char c=getchar();
while (c<''||c>'') {if (c=='-') f=-;c=getchar();}
while (c>=''&&c<='') x=(x<<)+(x<<)+(c^),c=getchar();
return x*f;
}
int n,m,a[N],p[N],deep[N],root[N],dfn[N],size[N],q[N],cnt,t,lastans,rt,d;
struct data{int to,nxt;
}edge[N<<];
struct data2{int l,r,x;
}tree[N<<];
void addedge(int x,int y){t++;edge[t].to=y,edge[t].nxt=p[x],p[x]=t;}
void dfs(int k,int from)
{
dfn[k]=++cnt;size[k]=;
for (int i=p[k];i;i=edge[i].nxt)
if (edge[i].to!=from)
{
deep[edge[i].to]=deep[k]+;
dfs(edge[i].to,k);
size[k]+=size[edge[i].to];
}
}
void ins(int &k,int l,int r,int p,int x)
{
tree[++cnt]=tree[k],k=cnt;tree[k].x=min(tree[k].x,x);
if (l==r) return;
int mid=l+r>>;
if (p<=mid) ins(tree[k].l,l,mid,p,x);
else ins(tree[k].r,mid+,r,p,x);
}
int query(int k,int l,int r,int x,int y)
{
if (!k) return inf;
if (l==x&&r==y) return tree[k].x;
int mid=l+r>>;
if (y<=mid) return query(tree[k].l,l,mid,x,y);
else if (x>mid) return query(tree[k].r,mid+,r,x,y);
else return min(query(tree[k].l,l,mid,x,mid),query(tree[k].r,mid+,r,mid+,y));
}
void bfs()
{
int head=,tail=;cnt=;tree[].x=inf;q[]=rt;
do
{
int x=q[++head];if (deep[x]&&deep[x]>deep[q[head-]]) root[deep[x]]=root[deep[x]-];
ins(root[deep[x]],,n,dfn[x],a[x]);
for (int i=p[x];i;i=edge[i].nxt)
if (deep[edge[i].to]>deep[x]) q[++tail]=edge[i].to;
}while (head<tail);
d=deep[q[tail]];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("cf893f.in","r",stdin);
freopen("cf893f.out","w",stdout);
const char LL[]="%I64d\n";
#else
const char LL[]="%lld\n";
#endif
n=read(),rt=read();
for (int i=;i<=n;i++) a[i]=read();
for (int i=;i<n;i++)
{
int x=read(),y=read();
addedge(x,y),addedge(y,x);
}
dfs(rt,rt);
bfs();
m=read();
while (m--)
{
int x=(read()+lastans)%n+,y=(read()+lastans)%n;
printf("%d\n",lastans=query(root[min(d,deep[x]+y)],,n,dfn[x],dfn[x]+size[x]-));
}
return ;
}