PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#LCA0000011. Tổ tiên thứ k của một đỉnh (Kth Ancestor of a Tree Node)
HỌC THEO LỘ TRÌNH
1 lộ trìnhBài tập thuộc lộ trình
Mục lục đề ⌄
Đang đọc
Tổ tiên thứ k của một đỉnh (Kth Ancestor of a Tree Node)
Kth Ancestor of a Tree Node
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
A rooted tree consists of vertices indexed from to , with root . Every other vertex has exactly one parent.
The -th ancestor of is obtained by following parent links exactly times. If the chain ends first, the ancestor does not exist.
Answer all -th ancestor queries. This Phuoc Hung OJ version uses standard input/output instead of the original class API.
Input
- The first line contains .
- The second line has integers , where and is vertex 's parent.
- The next lines contain .
Output
Print the ancestor index for each query, or -1 if absent.
Subtasks
- Subtask 1 (20 points): ; ; ; ; ; ; với .
- Subtask 2 (30 points): ; ; ; ; ; ; với .
- Subtask 3 (50 points): ; ; ; ; với .
Examples
Input
7 3
-1 0 0 1 1 2 2
3 1
5 2
6 3
Output
1
0
-1
Explanation
Vertex has parent ; the second ancestor of is ; the third ancestor of does not exist.