CSES - Shared codeLink to this code: https://cses.fi/paste/b25a36087ee60337595a61/
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define fast ios_base::sync_with_stdio(NULL);cin.tie(0);cout.tie(0)
#define F first
#define S second
#define yes cout << "YES\n"
#define no cout << "NO\n"
#define answer cout << ans1 << "\n"
#define db long double
using namespace std;
ll tt=1,n,m,a,b,c,w,ans2=1,ans1=0,h,sum=0,d,maxi=0,mini=0,mod2=998244353,mod=7+1e9,k;
const ll INF=1000000005,N=5+2e5,LOG=32;
bool f=0;
vector<ll> v,v2;
string s,t;
bool MASKisbit(int x, int y){return ((x & (1<<y)) ? 1 : 0);}
int MASKcnt(int x){int ans=0; for(int i=0;i<20;i++){ans+=x%2;x/=2;} return ans;}
ll power(ll aa,ll bb, ll momo){ll res=1;while(bb){if(bb%2)res=(res*aa)%momo;aa=(aa*aa)%momo;bb/=2;} return res;}
ll nextp2(ll x){bitset<30> bi=x;for(int i=30;i>0;i--)if(bi[i-1])return power(2,i,mod); return 1;}
ll modInverse(ll x,int p){return power(x, p - 2, p);}
ll gcd(ll a,ll b){if(b==0)return a;return gcd(b, a % b);}
ll lcm(ll a, ll b){return (a/gcd(a,b))*b;}
bool inside(int x,int y){return (x<=n && x>=1 && y>=1 && y<=m);}
int anc[N][LOG];
int kthancestor(int v,int k)
{
for(int i=0;i<LOG;++i)
{
if(k&(1<<i))
{
v=anc[v][i];
}
}
return v;
}
void solve()
{
cin >> n >> m;
for(int i=1;i<=n;++i){cin >> anc[i][0];}
for(int j=1;j<LOG;++j)
for(int i=1;i<=n;++i)
{
anc[i][j]=anc[anc[i][j-1]][j-1];
}
for(int i=0;i<m;++i)
{
cin >> a >> k;
cout << kthancestor(a,k) << "\n";
}
}
int main(){
fast;
///cin >> tt;
while(tt--)
{
solve();
}
return 0;
}