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

#LCA0000058. Họ hàng cùng bậc (Blood Cousins)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Họ hàng cùng bậc (Blood Cousins)

Blood Cousins

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

A genealogy contains nn people; every person has at most one immediate parent. The parent relations are acyclic and may form several separate rooted family trees.

Two distinct people x,yx,y are called pp-th cousins if they have the same ancestor after moving exactly pp parent links upward from each. For each query (v,p)(v,p), count how many people other than vv are pp-th cousins of vv. If vv has no pp-th ancestor, answer 00.

Input

  • The first line contains nn.
  • The second line contains nn integers p1,…,pnp_1,\ldots,p_n, where pip_i is the immediate parent of person ii or 00 if none exists.
  • The third line contains qq.
  • The next qq lines contain pairs v,pv,p.

Output

Print qq integers in query order, separated by spaces.

Subtasks

General constraints: 1≤n,q≤1051\le n,q\le10^5; 0≤pi≤n0\le p_i\le n; 1≤v,p≤n1\le v,p\le n; quan hệ cha không có chu trình.

  • Subtask 1 (20 points): 1≤n≤401\le n\le 40; 1≤q≤501\le q\le 50.

  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.

  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 1≤q≤1000001\le q\le 100000.

Examples

Input

6
0 1 1 0 4 4
7
1 1
1 2
2 1
2 2
4 1
5 1
6 1

Output

0 0 1 0 0 1 1

Explanation

The family forest has roots 11 (children 2,32,3) and 44 (children 5,65,6). Person 11 has no ancestor one or two levels up, producing two zeros. Person 22 shares parent 11 with person 33, so (2,1)(2,1) gives 11, but (2,2)(2,2) gives 00. Person 44 has no parent; people 55 and 66 share parent 44, giving 11 for each of their queries.