#E. ABC202E - Count Descendants

    Type: Default 1000ms 256MiB

ABC202E - Count Descendants

You cannot submit for this problem because the contest is ended. You can click "Open in Problem Set" to view this problem in normal mode.

Score : 500 points

Problem Statement

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

Vertex 1 is the root, and the parent of Vertex i(2iN) is Vertex Pi.

You are given Q queries. In the i-th query (1iQ), given integers Ui and Di, find the number of vertices u that satisfy all of the following conditions:

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

Constraints

  • 2N2×105
  • 1Pi<i
  • 1Q2×105
  • 1UiN
  • 0DiN1
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P2 P3  PN
Q
U1 D1
U2 D2

UQ DQ

Output

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


Sample Input 1

7
1 1 2 2 4 2
4
1 2
7 2
4 1
5 5

Sample Output 1

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

ABC202

Not Attended
Status
Done
Rule
IOI
Problem
7
Start at
2023-6-28 14:15
End at
2023-6-28 16:39
Duration
2.4 hour(s)
Host
Partic.
13