atcoder#ABC202E. [ABC202E] Count Descendants

[ABC202E] Count Descendants

Score : 500500 points

Problem Statement

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

Vertex 11 is the root, and the parent of Vertex i(2iN)i \, (2 \leq i \leq N) is Vertex PiP_i.

You are given QQ queries. In the ii-th query (1iQ)(1 \leq i \leq Q), given integers UiU_i and DiD_i, find the number of vertices uu that satisfy all of the following conditions:

  • Vertex UiU_i is in the shortest path from uu to the root (including the endpoints).
  • There are exactly DiD_i edges in the shortest path from uu to the root.

Constraints

  • 2N2×1052 \leq N \leq 2 \times 10^5
  • 1Pi<i1 \leq P_i < i
  • 1Q2×1051 \leq Q \leq 2 \times 10^5
  • 1UiN1 \leq U_i \leq N
  • 0DiN10 \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 QQ lines. The ii-th line should contain the response to the ii-th query.

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

In the 11-st query, Vertices 44, 55, and 77 satisfy the conditions. In the 22-nd query, only Vertices 77 satisfies the conditions. In the 33-rd and 44-th queries, no vertice satisfies the conditions.

sample