Employee Complaints Management

2

1 votes
Loops, Tree, approved, Medium-Hard
Problem

ABC company is building an Employee Complaint Management (ECM) system. Currently the company has N employees. Each employee is identified with his/her employee ID which is an integer between 1 to N. Each employee has exactly one boss, except the employee with employee ID 1, the owner of the company. The structure is hierarchical i.e. an employee will be a boss of all the subordinates of his/her subordinates. Currently the ECM has following two features:

  1. Help Employees make complaints. Any employee A can complain about any other employee B to any of their common bosses.
  2. Help Employees track the status of their complaints.

Now they want to add one more feature. They want to add a recommendation system. If any employee wants to make a complaint against any other employee, it will recommend them the Employee ID of their common boss having the maximum Justice Factor. They calculate the Justice Factor for employees using ML Techniques. They'll provide you the current value of Justice Factor for all the employees, they just want you to write an optimal program such that given a lots of queries of type x y, meaning that employee ID x wants to complain about employee ID y, it returns the employee ID of their common bosses having the maximum Justice Factor.

Input Format:
First line consists of a single integer denoting N.
Second line consists of N space separated integers where the ith(1iN) integer denotes the Justice Factor of employee having ID i.
Third line consists of N1 space separated integers denoting the boss's employee ID of all employees having ID between 2 to N.
Fourth line consists of a single integer Q, denoting the number of queries.
Following Q lines consists of two space separated integers x y denoting that employee x wants to complain about employee y.

Output Format:
For each query, print the ID of the common boss of x and y having maximum Justice Factor in a new line.

Constraints:
1N,Q105
1X,YN

Note: It is ensured that no two employees have same value of the Justice Factor, and that no employee will ever want to make a complaint about one of their bosses.

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

4 and 5 have two common bosses, having ID 1 and 2, out of those 2 is having the maximum Justice Factor.
5 and 3 have only one common boss i.e. 1, so that is the answer.

Editor Image

?