#P10113. Finding the Maximum Manager in a Company

    ID: 12099 Type: Default 1000ms 256MiB

Finding the Maximum Manager in a Company

Finding the Maximum Manager in a Company

Given a company with \(N\) employees numbered from \(0\) to \(N-1\), employee \(0\) is the boss and every other employee \(i\) (\(1 \le i \le N-1\)) has a direct manager denoted by \(f_i\). An employee \(x\) can manage employee \(y\) if and only if one of the following holds:

  • \(x = y\);
  • \(x = f_y\) (i.e. \(x\) is the direct manager of \(y\));
  • \(x\) can manage \(f_y\) (i.e. management is transitive).

Note that the boss (employee 0) can only be managed by himself. In other words, if \(y=0\) then only \(x=0\) satisfies the condition.

A group of colleagues wishes to collaborate and they need to select a host. The selected host must be able to manage every one of the participating employees following the rules above. If there are multiple valid hosts, choose the one with the largest employee number. Your task is to find such a host.

Input Format: The input consists of multiple lines. The first line contains an integer \(N\) (the number of employees). The second line contains \(N-1\) space-separated integers: \(f_1, f_2, \ldots, f_{N-1}\) (the direct manager for each employee from \(1\) to \(N-1\); note that employee \(0\) is the boss and has no manager). The third line contains an integer \(M\) representing the number of participating employees. The fourth line contains \(M\) space-separated integers representing the IDs of the participants.

Output Format: Output a single integer representing the ID of the selected host.

Note: An employee \(x\) can manage employee \(y\) if \(x\) is in the management chain of \(y\) (including \(y\) itself). For example, if the chain of command for an employee \(y\) is \(y, f_y, f_{f_y}, \ldots, 0\), then any employee in this chain can manage \(y\), with the boss (employee 0) being able to indirectly manage employees whose chain eventually reaches 0. However, since employee 0 can only be managed by himself, no one else can manage employee 0.

inputFormat

The input is given as follows:

  1. An integer \(N\) (\(1 \leq N \leq 10^5\)) denoting the number of employees.
  2. \(N-1\) space-separated integers \(f_1, f_2, \ldots, f_{N-1}\) where \(f_i\) is the direct manager of employee \(i\) (\(1 \le i \le N-1\)).
  3. An integer \(M\) denoting the number of participating employees.
  4. \(M\) space-separated integers representing the IDs of the participating employees.

outputFormat

Output a single integer which is the ID of the employee who can manage all participating employees. If multiple employees satisfy the condition, output the one with the largest ID.

sample

5
0 0 1 1
2
3 4
1