PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#LCA0000028. Cấp trên chung gần nhất (Company Queries II)
HỌC THEO LỘ TRÌNH
1 lộ trìnhBài tập thuộc lộ trình
Mục lục đề ⌄
Đang đọc
Cấp trên chung gần nhất (Company Queries II)
Company Queries II
Source: CSES
Version: Phuoc Hung OJ Extended
Problem Statement
A company has employees numbered from to . Employee is the director; every other employee has exactly one direct boss. The hierarchy forms a tree rooted at .
For each employee pair , find their lowest common boss, counting an employee as their own ancestor.
Input
- First line: .
- Second line: values , where is the immediate boss of .
- The next lines each contain .
Output
Print the lowest common boss for every query, one per line.
Subtasks
General constraints (all subtasks): ; ; .
- Subtask 1 (20 points): ; .
- Subtask 2 (30 points): ; .
- Subtask 3 (50 points): ; .
Examples
Input
5 3
1 1 3 3
4 5
2 5
1 4
Output
3
1
1
Explanation
Employees share ancestor . The two remaining query pairs have LCA .