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

#LCA0000011. Tổ tiên thứ k của một đỉnh (Kth Ancestor of a Tree Node)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổ tiên thứ k của một đỉnh (Kth Ancestor of a Tree Node)

Kth Ancestor of a Tree Node

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A rooted tree consists of nn vertices indexed from 00 to n−1n-1, with root 00. Every other vertex has exactly one parent.

The kk-th ancestor of uu is obtained by following parent links exactly kk times. If the chain ends first, the ancestor does not exist.

Answer all kk-th ancestor queries. This Phuoc Hung OJ version uses standard input/output instead of the original class API.

Input

  • The first line contains n,qn,q.
  • The second line has nn integers p0,p1,…,pn−1p_0,p_1,\ldots,p_{n-1}, where p0=−1p_0=-1 and pip_i is vertex ii's parent.
  • The next qq lines contain u,ku,k.

Output

Print the ancestor index for each query, or -1 if absent.

Subtasks

  • Subtask 1 (20 points): n≤30n\le30; q≤60q\le60; 1≤n,q≤5⋅1041\le n,q\le5\cdot10^4; 1≤k≤n1\le k\le n; 0≤u<n0\le u<n; p0=−1p_0=-1; 0≤pi<i0\le p_i<i với i>0i>0.
  • Subtask 2 (30 points): n≤1000n\le1000; q≤3000q\le3000; 1≤n,q≤5⋅1041\le n,q\le5\cdot10^4; 1≤k≤n1\le k\le n; 0≤u<n0\le u<n; p0=−1p_0=-1; 0≤pi<i0\le p_i<i với i>0i>0.
  • Subtask 3 (50 points): 1≤n,q≤5⋅1041\le n,q\le5\cdot10^4; 1≤k≤n1\le k\le n; 0≤u<n0\le u<n; p0=−1p_0=-1; 0≤pi<i0\le p_i<i với i>0i>0.

Examples

Input

7 3
-1 0 0 1 1 2 2
3 1
5 2
6 3

Output

1
0
-1

Explanation

Vertex 33 has parent 11; the second ancestor of 55 is 00; the third ancestor of 66 does not exist.