#LCA0000058. Họ hàng cùng bậc (Blood Cousins)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Họ hàng cùng bậc (Blood Cousins)
Blood Cousins
Source: Codeforces
Version: Phuoc Hung OJ Extended
Problem Statement
A genealogy contains 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 are called -th cousins if they have the same ancestor after moving exactly parent links upward from each. For each query , count how many people other than are -th cousins of . If has no -th ancestor, answer .
Input
- The first line contains .
- The second line contains integers , where is the immediate parent of person or if none exists.
- The third line contains .
- The next lines contain pairs .
Output
Print integers in query order, separated by spaces.
Subtasks
General constraints: ; ; ; quan hệ cha không có chu trình.
-
Subtask 1 (20 points): ; .
-
Subtask 2 (30 points): ; .
-
Subtask 3 (50 points): ; .
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 (children ) and (children ). Person has no ancestor one or two levels up, producing two zeros. Person shares parent with person , so gives , but gives . Person has no parent; people and share parent , giving for each of their queries.