PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000008. Đếm con cháu ở độ sâu chỉ định (Count Descendants)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đếm con cháu ở độ sâu chỉ định (Count Descendants)

Count Descendants

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

A rooted tree has nn vertices with root 11. The root has depth 00, and every other vertex has its parent's depth plus 11.

For each query (u,d)(u,d), count vertices vv in the subtree rooted at uu (including uu) whose depth measured from root 11 is exactly dd.

The value dd is not the distance from uu to vv.

Input

  • The first line contains nn.
  • The second line contains n−1n-1 parent indices p2,…,pnp_2,\ldots,p_n.
  • The next line contains qq.
  • Each of the next qq lines contains u,du,d.

Output

Print one count per query, each on a separate line.

Subtasks

  • Subtask 1 (20 points): n≤30n\le30; q≤60q\le60; 2≤n≤2⋅1052\le n\le2\cdot10^5; 1≤q≤2⋅1051\le q\le2\cdot10^5; 1≤pi<i1\le p_i<i; 0≤d≤n−10\le d\le n-1.
  • Subtask 2 (30 points): n≤1000n\le1000; q≤3000q\le3000; 2≤n≤2⋅1052\le n\le2\cdot10^5; 1≤q≤2⋅1051\le q\le2\cdot10^5; 1≤pi<i1\le p_i<i; 0≤d≤n−10\le d\le n-1.
  • Subtask 3 (50 points): 2≤n≤2⋅1052\le n\le2\cdot10^5; 1≤q≤2⋅1051\le q\le2\cdot10^5; 1≤pi<i1\le p_i<i; 0≤d≤n−10\le d\le n-1.

Examples

Input

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

Output

3
1
0
0

Explanation

In the example, there are three depth-22 descendants of vertex 11. The subtree of vertex 77 contains itself at depth 22. The last two queries return 00.