CSES - Shared codeLink to this code: https://cses.fi/paste/01de614e8a6ad46137e5fa/
#include <iostream>

int const lgmax = 20;
int const nmax = 200000;
int far[1 + lgmax][1 + nmax];

int main() {
  int n, q;
  std::cin >> n >> q;
  for(int i = 2;i <= n; i++)
    std::cin >> far[0][i];

  for(int h = 1; h <= lgmax; h++)
    for(int i = 1;i <= n; i++)
      far[h][i] = far[h - 1][far[h - 1][i]];

  for(int i = 1;i <= q; i++) {
    int x, k;
    std::cin >> x >> k;
    for(int h = lgmax; 0 <= h; h--)
      if((1 << h) <= k) {
        x = far[h][x];
        k -= (1 << h);
      }
    if(x == 0)
      std::cout << -1 << '\n';
    else
      std::cout << x << '\n';
  }
}