题目描述
Problem Description
A company has $N$ employees, numbered from $0$ to $N-1$. Among them, except for the $0$th employee who is the boss, each employee has a direct supervisor. We assume that the direct supervisor of the employee numbered $i$ is $f_i$.
The company has a strict management system where each employee can only be managed by themselves, their direct supervisor, or their indirect supervisor. Specifically, employee $x$ can manage employee $y$ if and only if $x = y$, or $x = f_y$, or $x$ can manage $f_y$. Notably, the $0$th employee, the boss, can only manage themselves and cannot be managed by any other employee.
Now, some colleagues are going to collaborate and they want to find a colleague to lead this collaboration. This colleague must be able to manage all the participating colleagues. If there are multiple employees who meet this condition, they want to find the one with the highest number. Can you help them?
Input Format
The first line contains an integer $N$, representing the number of employees.
The second line contains $N-1$ positive integers separated by spaces, representing $f_1, f_2, \dots, f_{N-1}$ in order.
The third line contains an integer $Q$, representing the number of collaborations that need to be arranged.
The next $Q$ lines describe each collaboration: the first is an integer $m$ ($2 \leq m \leq N$), representing the number of employees participating in this collaboration; followed by $m$ integers representing the employee numbers participating in this collaboration (guaranteed to be valid and non-repeating).
It is guaranteed that the company structure is valid, meaning no employee is their own direct or indirect supervisor.
Output Format
Output $Q$ lines, each containing an integer, representing the host for each collaboration in order.
Sample Input and Output
Input Sample #1
5
0 0 2 2
3
2 3 4
3 2 3 4
2 1 4
Output Sample #1
2
2
0
Input Sample #2
7
0 1 0 2 1 2
5
2 4 6
2 4 5
3 4 5 6
4 2 4 5 6
2 3 4
Output Sample #2
2
1
1
1
0
Notes
Sample Explanation 1
For the first collaboration, employees $3$ and $4$ have a common supervisor $2$, who can host the collaboration.
For the second collaboration, employee $2$ can manage all participants.
For the third collaboration, only the boss, employee $0$, can manage all employees.
Data Range
For $25\%$ of the test cases, $N \leq 50$.
For $50\%$ of the test cases, $N \leq 300$.
For all test cases, $3 \leq N \leq 10^5$, $Q \leq 100$, $m \leq 10^4$.
Added a set of hack data on February 8, 2024.
输入格式
见题面 Input 部分
输出格式
见题面 Output 部分