PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000028. Cấp trên chung gần nhất (Company Queries II)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Cấp trên chung gần nhất (Company Queries II)

Company Queries II

Source: CSES

Version: Phuoc Hung OJ Extended

Problem Statement

A company has nn employees numbered from 11 to nn. Employee 11 is the director; every other employee has exactly one direct boss. The hierarchy forms a tree rooted at 11.

For each employee pair a,ba,b, find their lowest common boss, counting an employee as their own ancestor.

Input

  • First line: n,qn,q.
  • Second line: n−1n-1 values p2,…,pnp_2,\ldots,p_n, where pip_i is the immediate boss of ii.
  • The next qq lines each contain a,ba,b.

Output

Print the lowest common boss for every query, one per line.

Subtasks

General constraints (all subtasks): 1≤n,q≤2⋅1051\le n,q\le 2\cdot 10^5; 1≤pi<i1\le p_i<i; 1≤a,b≤n1\le a,b\le n.

  • Subtask 1 (20 points): 1≤n≤301\le n\le 30; 1≤q≤501\le q\le 50.
  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.
  • Subtask 3 (50 points): 1≤n≤2000001\le n\le 200000; 1≤q≤2000001\le q\le 200000.

Examples

Input

5 3
1 1 3 3
4 5
2 5
1 4

Output

3
1
1

Explanation

Employees 4,54,5 share ancestor 33. The two remaining query pairs have LCA 11.