PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#LCA0000009. Truy vấn cấp trên thứ k (Company Queries I)
HỌC THEO LỘ TRÌNH
1 lộ trìnhBài tập thuộc lộ trình
Mục lục đề ⌄
Đang đọc
Truy vấn cấp trên thứ k (Company Queries I)
Company Queries I
Source: CSES
Version: Phuoc Hung OJ Extended
Problem Statement
A company has employees numbered to . Employee is the director and has no manager. The other employees form a hierarchy rooted at employee .
The first ancestor of is their immediate manager; the second is that manager's manager, and so forth.
For each query , find the -th ancestor of . If it does not exist, output -1.
Input
- The first line contains .
- The second line contains parent indices .
- Each of the next lines contains .
Output
Print each ancestor on its own line, or -1 if it does not exist.
Subtasks
- Subtask 1 (20 points): ; ; ; ; ; .
- Subtask 2 (30 points): ; ; ; ; ; .
- Subtask 3 (50 points): ; ; ; .
Examples
Input
5 3
1 1 3 3
4 1
4 2
4 3
Output
3
1
-1
Explanation
The immediate manager of is , its second ancestor is , and its third ancestor does not exist, giving .