CSES - Shared codeLink to this code:
https://cses.fi/paste/a7e650ba89b7e0e037e879/
#include <iostream>
#include <vector>
using ll = long long;
int const nmax = 200000;
int parent[1 + nmax];
int far[1 + nmax];
int level[1 + nmax];
int main() {
int n, q;
std::cin >> n >> q;
for(int i = 2; i <= n; i++)
std::cin >> parent[i];
level[1] = 1;
for(int i = 2; i <= n; i++) {
level[i] = level[parent[i]] + 1;
int father = parent[i];
int father2 = far[father];
if(far[father2] != 0 && level[father] - level[father2] == level[father2] - level[far[father2]]) {
far[i] = far[father2];
} else
far[i] = father;
}
for(int i = 1;i <= q; i++) {
int node, k;
std::cin >> node >> k;
while(0 < k && 0 < node) {
if(level[node] - k <= level[far[node]]) {
k -= level[node] - (level[far[node]]);
node = far[node];
} else {
k --;
node = parent[node];
}
}
if(node == 0)
std::cout << -1 << '\n';
else
std::cout << node << '\n';
}
return 0;
}