题目收集
题目列表题单
返回列表

Subtree Capacity

CodeforcesP0026· 3000ms· 256 MB· ZJU Summer 2026 Contest 2原题链接
贪心树上问题数据结构优化

创建于 2026/07/16 · 更新于 2026/07/16

题目描述

You are given a rooted tree with nnn vertices, rooted at vertex 111. Vertex iii has a non-negative integer capacity aia_iai​.

You may choose a set SSS of vertices (any subset of the vertices). The set SSS is called valid if, for every vertex iii of the tree, the number of chosen vertices lying in the subtree of iii is at most aia_iai​:

∣S∩subtree(i)∣≤aifor all i=1,2,…,n,|S \cap \mathrm{subtree}(i)| \le a_i \qquad \text{for all } i = 1, 2, \dots, n,∣S∩subtree(i)∣≤ai​for all i=1,2,…,n,

where subtree(i)\mathrm{subtree}(i)subtree(i) is the subtree rooted at iii (including iii itself).

You must answer qqq queries. Each query gives two integers lll and rrr. For this query, you may only choose vertices whose index lies in [l,r][l, r][l,r], i.e. S⊆{l,l+1,…,r}S \subseteq \{l, l+1, \dots, r\}S⊆{l,l+1,…,r}; however, the capacity constraint above still applies to every vertex of the tree. Report the maximum possible size ∣S∣|S|∣S∣ of a valid set.

Note. The capacity constraint holds for all nnn vertices, not only for the vertices with index in [l,r][l, r][l,r]. In particular, a vertex u∉[l,r]u \notin [l, r]u∈/[l,r] (such as a common ancestor or the root) still limits how many chosen vertices its subtree may contain.

输入格式

The first line contains two integers nnn and qqq.

The second line contains nnn integers a1,a2,…,ana_1, a_2, \dots, a_na1​,a2​,…,an​.

The third line contains n−1n-1n−1 integers p2,p3,…,pnp_2, p_3, \dots, p_np2​,p3​,…,pn​, where pip_ipi​ is the parent of vertex iii.

Each of the next qqq lines contains two integers lll and rrr.

2≤n≤2⋅1052 \le n \le 2\cdot10^52≤n≤2⋅105, 1≤q≤2⋅1051 \le q \le 2\cdot10^51≤q≤2⋅105, 0≤ai≤n0 \le a_i \le n0≤ai​≤n, and 1≤pi≤n1 \le p_i \le n1≤pi​≤n where the parents describe a tree rooted at vertex 111. For each query, 1≤l≤r≤n1 \le l \le r \le n1≤l≤r≤n.

输出格式

For each query, output a single line containing the maximum size of a valid chosen set.

样例输入 #1

8 4
4 1 2 1 1 1 1 1
1 1 2 2 3 3 1
1 8
4 8
4 5
6 7

样例输出 #1

4
4
1
2

样例输入 #2

4 2
2 0 1 2
1 1 2
1 4
4 4

样例输出 #2

2
0