Pagini recente » Cod sursa (job #735136) | Cod sursa (job #2691258) | Cod sursa (job #2059646) | Cod sursa (job #146943) | Cod sursa (job #2099700)
#include <bits/stdc++.h>
#define N 250100
using namespace std;
ifstream in("stramosi.in");
ofstream out("stramosi.out");
int n, m, x, y, q, dad[N], anc[20][N];
bool viz[N], root[N];
void build(){
int sz = log2(n);
for(int i = 1; i <= n; i++)
anc[0][i] = i;
for(int lvl = 1; lvl <= sz; lvl++)
for(int i = 1; i <= n; i++)
x = anc[lvl - 1][i], anc[lvl][i] = anc[lvl - 1][dad[x]];
}
void solve(){
in >> x >> y;
if(anc[(int)log2(y)][x] == 0){
out << "0\n";
return;
}
int cnt = 0;
while(cnt < y && dad[x] != 0){
int lvl = 1;
while(cnt + (1 << lvl) - 1 <= y && anc[lvl][x] != 0){
cnt += (1 << lvl) - 1;
x = anc[lvl][x];
lvl++;
}
}
out << (cnt == y ? x : 0) << '\n';
}
int main(){
ios_base :: sync_with_stdio(0);
in.tie(0);
out.tie(0);
in >> n >> q;
for(int i = 1; i <= n; i++){
in >> x;
if(x == 0)
continue;
dad[i] = x;
}
build();
while(q--)
solve();
return 0;
}