在子树内和距离不超过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<'0'||c>'9')) c=getchar();return c;} int gcd(int n,int m){return m==0?n:gcd(m,n%m);} int read() { int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),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<<1]; struct data2{int l,r,x; }tree[N<<5]; 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]=1; for (int i=p[k];i;i=edge[i].nxt) if (edge[i].to!=from) { deep[edge[i].to]=deep[k]+1; 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>>1; if (p<=mid) ins(tree[k].l,l,mid,p,x); else ins(tree[k].r,mid+1,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>>1; if (y<=mid) return query(tree[k].l,l,mid,x,y); else if (x>mid) return query(tree[k].r,mid+1,r,x,y); else return min(query(tree[k].l,l,mid,x,mid),query(tree[k].r,mid+1,r,mid+1,y)); } void bfs() { int head=0,tail=1;cnt=0;tree[0].x=inf;q[1]=rt; do { int x=q[++head];if (deep[x]&&deep[x]>deep[q[head-1]]) root[deep[x]]=root[deep[x]-1]; ins(root[deep[x]],1,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 "; #else const char LL[]="%lld "; #endif n=read(),rt=read(); for (int i=1;i<=n;i++) a[i]=read(); for (int i=1;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+1,y=(read()+lastans)%n; printf("%d ",lastans=query(root[min(d,deep[x]+y)],1,n,dfn[x],dfn[x]+size[x]-1)); } return 0; }