CSES - Shared codeLink to this code: https://cses.fi/paste/bcb43538ce2e113b37e801/
#include <iostream>
 
int const lgmax = 7;
int const nmax = 200000;
int const base = 5;
int far[1 + lgmax][1 + nmax];
int powp[1 + lgmax];

int main() {
  int n, q;
  std::cin >> n >> q;
  for(int i = 2;i <= n; i++)
    std::cin >> far[0][i];
  
  powp[0] = 1;
  for(int i = 1;i <= lgmax; i++)
    powp[i] = powp[i - 1] * base;

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

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