CSES - Shared codeLink to this code: https://cses.fi/paste/9453356b4844de3d5d6e7a/
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define IOS ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>order_set;
typedef pair<int, int>pr;
#define all(i) i.begin() , i.end()
#define ft first
#define sn second
#define pb push_back
#define en "\n"
#define dbg cout<<"rony\n"
#define MAXN 200010
#define inf 1e6+5
const ll mod = 1e9 + 7;
int n, q;
int up[MAXN][20];
void solve()
{
cin >> n >> q;
for (int i = 2; i <= n; i++) {
cin >> up[i][0];
}
for (int log = 1; log < 20; log++)
{
for (int i = 1; i <= n; i++) {
int ancestor = up[i][log - 1];
up[i][log] = up[ancestor][log - 1];
}
}
while (q--)
{
int v, k;
cin >> v >> k;
for (int log = 19; log >= 0; log--)
{
if (k >= (1 << log)) {
k -= (1 << log);
v = up[v][log];
}
}
if (v == 0) cout << -1 << en;
else cout << v << en;
}
}
int main()
{
IOS;
ll t;
t = 1;
// cin >> t;
int c = 0;
while ( t-- )
{
// cout<<"Case "<<++c<<": ";
solve();
}
return 0;
}