炒鸡大水题,套路得要死(
看到「子树」,就有线段树合并和 DFS 序——考虑到维护的最小值没有区间减法,使用线段树合并。
强制在线,可持久化一下就好了。
代码: 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
using namespace std;
const int N = 1e5;
int n,m,r;
int a[N + 5];
int to[(N << 1) + 5],pre[(N << 1) + 5],first[N + 5];
int lastans;
inline void add(int u,int v)
{
static int tot = 0;
to[++tot] = v,pre[tot] = first[u],first[u] = tot;
}
struct node
{
int min;
int ls,rs;
} seg[(N << 7) + 10];
int rt[N + 5];
int seg_tot;
void insert(int x,int k,int &p,int tl,int tr)
{
if(!p)
p = ++seg_tot,seg[p].min = 0x3f3f3f3f;
seg[p].min = min(seg[p].min,k);
if(tl == tr)
return ;
int mid = tl + tr >> 1;
x <= mid ? insert(x,k,seg[p].ls,tl,mid) : insert(x,k,seg[p].rs,mid + 1,tr);
}
int query(int l,int r,int p,int tl,int tr)
{
if(!p || (l <= tl && tr <= r))
return seg[p].min;
int mid = tl + tr >> 1;
int ret = 0x3f3f3f3f;
if(l <= mid)
ret = min(ret,query(l,r,seg[p].ls,tl,mid));
if(r > mid)
ret = min(ret,query(l,r,seg[p].rs,mid + 1,tr));
return ret;
}
int merge(int x,int y)
{
if(!x || !y)
return x | y;
int p = ++seg_tot;
seg[p].min = min(seg[x].min,seg[y].min);
seg[p].ls = merge(seg[x].ls,seg[y].ls),seg[p].rs = merge(seg[x].rs,seg[y].rs);
return p;
}
int fa[N + 5],dep[N + 5];
void dfs(int p)
{
insert(dep[p],a[p],rt[p],1,n);
for(register int i = first[p];i;i = pre[i])
if(to[i] ^ fa[p])
fa[to[i]] = p,dep[to[i]] = dep[p] + 1,dfs(to[i]),rt[p] = merge(rt[p],rt[to[i]]);
}
int main()
{
seg[0].min = 0x3f3f3f3f;
scanf("%d%d",&n,&r);
for(register int i = 1;i <= n;++i)
scanf("%d",a + i);
int u,v;
for(register int i = 1;i < n;++i)
scanf("%d%d",&u,&v),add(u,v),add(v,u);
dep[r] = 1,dfs(r);
scanf("%d",&m);
int x,k;
while(m--)
{
scanf("%d%d",&x,&k);
x = (x + lastans) % n + 1,k = (k + lastans) % n;
printf("%d\n",lastans = query(dep[x],min(dep[x] + k,n),rt[x],1,n));
}
}