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

#LCA0000009. Truy vấn cấp trên thứ k (Company Queries I)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Truy vấn cấp trên thứ k (Company Queries I)

Company Queries I

Source: CSES

Version: Phuoc Hung OJ Extended

Problem Statement

A company has nn employees numbered 11 to nn. Employee 11 is the director and has no manager. The other employees form a hierarchy rooted at employee 11.

The first ancestor of xx is their immediate manager; the second is that manager's manager, and so forth.

For each query (x,k)(x,k), find the kk-th ancestor of xx. If it does not exist, output -1.

Input

  • The first line contains n,qn,q.
  • The second line contains n−1n-1 parent indices p2,…,pnp_2,\ldots,p_n.
  • Each of the next qq lines contains x,kx,k.

Output

Print each ancestor on its own line, or -1 if it does not exist.

Subtasks

  • Subtask 1 (20 points): n≤30n\le30; q≤60q\le60; 1≤n,q≤2⋅1051\le n,q\le2\cdot10^5; 1≤pi<i1\le p_i<i; 1≤x≤n1\le x\le n; 1≤k≤n1\le k\le n.
  • Subtask 2 (30 points): n≤1000n\le1000; q≤3000q\le3000; 1≤n,q≤2⋅1051\le n,q\le2\cdot10^5; 1≤pi<i1\le p_i<i; 1≤x≤n1\le x\le n; 1≤k≤n1\le k\le n.
  • Subtask 3 (50 points): 1≤n,q≤2⋅1051\le n,q\le2\cdot10^5; 1≤pi<i1\le p_i<i; 1≤x≤n1\le x\le n; 1≤k≤n1\le k\le n.

Examples

Input

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

Output

3
1
-1

Explanation

The immediate manager of 44 is 33, its second ancestor is 11, and its third ancestor does not exist, giving 3,1,−13,1,-1.