Pagini recente » Cod sursa (job #1354724) | Cod sursa (job #46258) | Cod sursa (job #25375) | Cod sursa (job #14397) | Cod sursa (job #3291458)
#include <iostream>
#include <vector>
using namespace std;
#define NMAX 250001
#define LOGMAX 17
int dp[LOGMAX+1][NMAX];
int n, q, par[NMAX], lvl[NMAX];
vector<int> g[NMAX];
void dfs(int r, int p, int l=0){
lvl[r]=l;
dp[0][r]=p;
for (int k=1; (1<<k)<=l; ++k){
dp[k][r]=dp[k-1][dp[k-1][r]];
}
for (auto it:g[r]){
if (it==p)continue;
dfs(it, r, l+1);
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
freopen("stramosi.in", "r", stdin);
freopen("stramosi.out", "w", stdout);
cin>>n>>q;
for (int i=1; i<=n; ++i){
cin>>par[i];
dp[0][i]=par[i];
g[par[i]].push_back(i);
g[i].push_back(par[i]);
}
//for (auto it:g[0]){dfs(it, 0);
for (int i=1; (1<<i)<=n; ++i){
for (int j=1; j<=n; ++j){
dp[i][j]=dp[i-1][dp[i-1][j]];
}
}
while (q--){
int x, y;
cin>>x>>y;
int curr=x;
for (int k=0; (1<<k)<=y; ++k){
if ((1<<k)&y){
curr=dp[k][curr];
}
}
cout<<curr<<"\n";
}
return 0;
}