#BS0000225. Tổ tiên của tôi (My Ancestor)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Tổ tiên của tôi (My Ancestor)
My Ancestor
Source: Phước Hưng OJ
Version: Phuoc Hung OJ Extended
Problem Statement
An independently specified Phuoc Hung OJ exercise inspired by the My Ancestor model in Competitive Programming. Vertex numbering, value bounds and query format are defined for this version.
A tree has vertices numbered from to and is rooted at vertex . Each vertex has an integer weight . For each vertex , its parent is . Weights strictly increase from parent to child: .
An ancestor of vertex is any vertex on the path from the root to , excluding itself. There are queries. Each query gives a vertex and a threshold . Find the ancestor of closest to the root such that . If no such ancestor exists, answer -1.
Input
The first line contains two integers .
The second line contains integers .
The third line contains integers , the parents of vertices through respectively. If , this line is empty.
Each of the following lines contains two integers describing one query.
Output
Print lines in query order. Each line contains the index of the qualifying ancestor closest to the root, or -1 if none exists.
Subtasks
- Subtask 1 (20 points): ; for every ; and for every ; , in every query.
- Subtask 2 (30 points): ; ; for every ; and for every ; , in every query.
- Subtask 3 (50 points): ; ; for every ; and for every ; , in every query.
Examples
Input
5 5
3 5 6 7 9
1 1 2 2
4 4
5 6
3 2
1 1
4 3
Output
2
-1
1
-1
1
Explanation
The tree has edges .
- Query : the ancestors of in root-to-vertex order are , with weights . Only vertex qualifies.
- Query : the ancestors of are , both with weights below . Vertex is not its own ancestor.
- Query : its only ancestor is vertex , with weight .
- Query : the root has no ancestors.
- Query : both vertices and qualify; vertex is closest to the root.