Tree Quiz

시간 제한4초메모리 제한1024 MB

요약
모든 순서쌍 (x, y)를 (x, LCA(x, y), y)로 부호화해 정렬한 배열에서 k번째 값을 묻는 질의에 답한다.
난이도

어려움10점 중 8점

유형
트리, DFS, 누적 합, 정렬
정답자
아직 제출이 없습니다

문제

Your friend wants to quiz you. You are given a rooted tree with nn nodes, numbered from 11 to nn. For every node ii, its parent is node p_ip\_i, except for the root (the node without a parent) which has p_i=0p\_i = 0. Node uu is an ancestor of node vv if either u=vu = v, or node uu is an ancestor of the parent of node vv (if it exists).

We say that node zz is a common ancestor of nodes xx and yy if node zz is an ancestor of both nodes xx and yy. We say that node zz is the lowest common ancestor of nodes xx and yy if it is a common ancestor of nodes xx and yy, and every common ancestor of nodes xx and yy is also an ancestor of node zz. We denote the lowest common ancestor of nodes xx and yy by LCA(x,y)LCA(x, y). In particular, LCA(x,x)=xLCA(x, x) = x.

Your friend would like to run the following pseudocode:

let L be an empty array
for x = 1 to n
  for y = 1 to n
    append ((x - 1) * n * n + (LCA(x, y) - 1) * n + (y - 1)) to L
sort L in non-decreasing order

Your friend has qq questions, numbered from 11 to qq. In question jj, you are given an integer k_jk\_j and asked to find the k_jk\_j-th element of the array LL. Note that LL is 11-indexed, so the indices range from 11 to n2n^2, inclusive. To pass the quiz, you have to answer all of the questions.

입력

The first line of input contains two integers nn and qq (1≤n≤100,0001 ≤ n ≤ 100\\, 000; 1≤q≤100,0001 ≤ q ≤ 100\\, 000). The second line contains nn integers p_1,p_2,…,p_np\_1, p\_2, \dots , p\_n (0≤p_i≤n0 ≤ p\_i ≤ n for all ii). It is guaranteed that the given values represent a rooted tree. Each of the next qq lines contains an integer. The jj-th line contains k_jk\_j (1≤k_j≤n21 ≤ k\_j ≤ n^2).

출력

For each question in order, output an integer representing the answer to the question.

예제1

  1. 예제 1

    입력
    5 3
    3 0 2 2 3
    1
    18
    25
    
    예상 출력
    0
    82
    124