Employee Complaints Management
Practice
2 (1 votes)
Loops
Tree
Approved
Medium Hard
Problem
43% Success 1518 Attempts 50 Points 1s Time Limit 256MB Memory 1024 KB Max Code

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 \space 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 \(i^{th}(1 \le i \le N)\) integer denotes the Justice Factor of employee having ID i.
Third line consists of \(N-1\) 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 \space 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:
\(1 \le N, Q \le 10^5\)
\(1 \le X, Y \le N\)

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.

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
5 votes
Tags:
Sparse TableTreeData StructuresMedium-HardLoopsSegment tree
Points:50
2 votes
Tags:
TreesBinary SearchData StructuresLowest Common AncestorSparse table
Points:50
7 votes
Tags:
Dynamic ProgrammingXORImplementationTreeTreesCombinatoricsData StructuresLowest Common AncestorMathematics
Editorial

No editorial available for this problem.