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

#LCA0000033. Thư viện truy vấn LCA tốc độ cao (Lowest Common Ancestor)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Thư viện truy vấn LCA tốc độ cao (Lowest Common Ancestor)

Lowest Common Ancestor

Source: Library Checker

Version: Phuoc Hung OJ Extended

Problem Statement

A tree rooted at vertex 00 has nn vertices indexed from 00 to n−1n-1. Every vertex i>0i>0 has a parent pi<ip_i<i.

Answer many lowest-common-ancestor queries LCA(u,v)(u,v). This is a library-style performance test with a potentially large number of nodes and queries. Each query satisfies u<vu<v.

Input

  • First line: n,qn,q.
  • Second line: parents p1,…,pn−1p_1,\ldots,p_{n-1}.
  • Next qq lines: query vertices u,vu,v with u<vu<v.

Output

Print each LCA in query order.

Subtasks

General constraints (all subtasks): 2≤n,q≤5⋅1052\le n,q\le 5\cdot 10^5; 0≤pi<i0\le p_i<i; 0≤u<v<n0\le u<v<n.

  • Subtask 1 (20 points): 2≤n≤302\le n\le 30; 1≤q≤501\le q\le 50.
  • Subtask 2 (30 points): 2≤n≤10002\le n\le 1000; 1≤q≤10001\le q\le 1000.
  • Subtask 3 (50 points): 2≤n≤5000002\le n\le 500000; 1≤q≤5000001\le q\le 500000.

Examples

Input

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

Output

0
0
0
2
2

Explanation

Query (2,3)(2,3) has LCA 22; (3,4)(3,4) lies within the subtree rooted at 22 and also has LCA 22.