Training Selection
Time limit1sMemory limit512 MB
Find the shortest index range [L, R] that contains at least one level-k subordinate for each request in a company tree.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Binary search, Two pointers
- Solved
- No attempts yet
Selecting the range
The employees of a company form a hierarchy. The company has employees, numbered from 1 to . The director has number 1. Every employee except the director has exactly one direct supervisor. The direct supervisor of employee has number , and .
Employee is a subordinate of level 1 of employee if . For , employee is a subordinate of level of employee if employee is a subordinate of level of employee .
The director wants to send some employees to a training course. He chooses two numbers and and sends every employee with .
Before choosing and , the director received requests. The -th request is a pair , and means that employee asks to send one of their subordinates of level to the course. To save money, the director wants the number of employees sent to the course to be as small as possible, while all requests are fulfilled. If several pairs are optimal, he chooses the one with the smallest .
Input
The first line contains , the number of employees (). The second line contains integers (), the direct supervisor of each employee . The third line contains , the number of requests. Each of the next lines contains two integers and (, ). It is guaranteed that employee has at least one subordinate of level .
Output
Print two integers and . If several pairs are optimal, print the pair with the smallest .
Hint
Employees 3, 4, 5, and 6 are sent to the course. Employee 3 is a subordinate of level 1 of employee 1. Employee 4 is a subordinate of level 2 of employee 1. Employee 6 is a subordinate of level 1 of employee 3.