#G. E - Count Descendants

    传统题 1000ms 256MiB

E - Count Descendants

该比赛已结束,您无法在比赛模式下递交该题目。您可以点击“在题库中打开”以普通模式查看和递交本题。

E - Count Descendants

Score : $500$ points

Problem Statement

We have a rooted tree with $N$ vertices, numbered $1, 2, \dots, N$.

Vertex $1$ is the root, and the parent of Vertex $i \, (2 \leq i \leq N)$ is Vertex $P_i$.

You are given $Q$ queries. In the $i$-th query $(1 \leq i \leq Q)$, given integers $U_i$ and $D_i$, find the number of vertices $u$ that satisfy all of the following conditions:

  • Vertex $U_i$ is in the shortest path from $u$ to the root (including the endpoints).
  • There are exactly $D_i$ edges in the shortest path from $u$ to the root.

Constraints

  • $2 \leq N \leq 2 \times 10^5$
  • $1 \leq P_i < i$
  • $1 \leq Q \leq 2 \times 10^5$
  • $1 \leq U_i \leq N$
  • $0 \leq D_i \leq N - 1$
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN

P2P_2 P3P_3 \ldots PNP_N

QQ

U1U_1 D1D_1

U2U_2 D2D_2

\vdots

UQU_Q DQD_Q

Output

Print $Q$ lines. The $i$-th line should contain the response to the $i$-th query.


7
1 1 2 2 4 2
4
1 2
7 2
4 1
5 5
3
1
0
0

In the $1$-st query, Vertices $4$, $5$, and $7$ satisfy the conditions. In the $2$-nd query, only Vertices $7$ satisfies the conditions. In the $3$-rd and $4$-th queries, no vertice satisfies the conditions.

sample

2024寒假入门组刷题营(十四)

未参加
状态
已结束
规则
ACM/ICPC
题目
8
开始于
2024-2-14 13:30
结束于
2024-2-14 15:30
持续时间
2 小时
主持人
参赛人数
9