Pagini recente » Borderou de evaluare (job #3245087) | Cod sursa (job #1989479) | Cod sursa (job #2864347) | Cod sursa (job #940378) | Cod sursa (job #921595)
Cod sursa(job #921595)
#include<cstdio>
#include<algorithm>
#define FOR(i,a,b)\
for(int i=a; i<=b; ++i)
#define infile "stramosi.in"
#define outfile "stramosi.out"
#define nMax 250005
#define logMax 20
using namespace std;
int P[logMax][nMax];
int N, M;
int ancestor(int x, int lev){
while(lev > 0){
int step = 0;
while(1 << (step + 1) < lev)
step ++;
x = P[step][x];
lev -= 1 << step;
}
return x;
}
int main(){
freopen(infile, "r", stdin);
freopen(outfile, "w", stdout);
scanf("%d %d", &N, &M);
FOR(i,1,N)
scanf("%d", &P[0][i]);
for(int j = 1; j <= N; ++j)
for(int i = 1; (1<<i) < N; ++i)
P[i][j] = P[i-1][P[i-1][j]];
int x, lev;
while(M--){
scanf("%d %d", &x, &lev);
printf("%d\n", ancestor(x, lev));
}
fclose(stdin);
fclose(stdout);
return 0;
}