Pagini recente » Cod sursa (job #523716) | Cod sursa (job #1789032) | Cod sursa (job #2082734) | Cod sursa (job #2084118) | Cod sursa (job #1695316)
#include <stdio.h>
#include <vector>
using namespace std;
const int MAX = 250005;
int n, m, x, y, p[MAX];
vector<int> l[MAX];
int anc(int x, int y){
int pow = 0;
while(y && x){
if(y & 1){
if(l[x].size() < pow + 1)
return 0;
x = l[x][pow];
}
pow++;
y >>= 1;
}
return x;
}
int main(){
freopen("stramosi.in", "r", stdin);
freopen("stramosi.out", "w", stdout);
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
scanf("%d", &p[i]);
for(int i = 1; i <= n; i++){
int x = i, niv = 0, pow = 0;
while(x){
x = p[x];
niv++;
if(niv & (1<<pow) && x){
l[i].push_back(x);
pow++;
}
}
}
for(int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
printf("%d\n", anc(x, y));
}
return 0;
}