#abc202e. E - Count Descendants

E - Count Descendants

Score : 500500 points

问题描述

我们有一棵包含 NN 个顶点的有根树,顶点编号为 1,2,,N1, 2, \dots, N

顶点 11 是树的根节点,且顶点 i(2iN)i \, (2 \leq i \leq N) 的父节点为顶点 PiP_i

你将得到 QQ 个查询。在第 ii 个查询 (1iQ)(1 \leq i \leq Q) 中,给定整数 UiU_iDiD_i,找出满足以下所有条件的顶点 uu 的数量:

  • 从顶点 uu 到根节点的最短路径中包含顶点 UiU_i(包括端点)。
  • 从顶点 uu 到根节点的最短路径中恰好包含 DiD_i 条边。

以上为通义千问 qwen-max 翻译,仅供参考。

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.

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 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

update @ 2024/3/10 09:14:45