CSES - Shared codeLink to this code: https://cses.fi/paste/347b0288460baae737e72c/
#include <iostream>
#include <vector>

using ll = long long;

int const nmax = 200000;
std::vector<int> g[5 + nmax];
std::vector<std::pair<int,int>> queries[5 + nmax];

int sol[5 + nmax];
std::vector<int> ancestors;

void dfs(int node) {
  ancestors.push_back(node);

  for(int h = 0; h < g[node].size(); h++) {
    int to = g[node][h];
    dfs(to);
  }
  
  for(int h = 0; h < queries[node].size(); h++) {
    int acc = queries[node][h].first;
    int id = queries[node][h].second;
    if(acc < ancestors.size())
      sol[id] = ancestors[ancestors.size() - acc - 1];
    else
      sol[id] = -1;
  }
  ancestors.pop_back();
}

int main() {
  int n, q;
  std::cin >> n >> q;
  for(int i = 2; i <= n; i++) {
    int x;
    std::cin >> x;
    g[x].push_back(i);
  }
  for(int i = 1;i <= q; i++) {
    int x, k;
    std::cin >> x >> k;
    queries[x].push_back({k, i});
  }
  dfs(1);

  for(int i = 1;i <= q; i++)
    std::cout << sol[i] << '\n';
  return 0;
}