Pagini recente » Cod sursa (job #484157) | Cod sursa (job #2483123) | Cod sursa (job #3229804) | Cod sursa (job #246648) | Cod sursa (job #1695367)
#include <stdio.h>
#include <vector>
using namespace std;
const int MAX = 250005;
int n, m, x, y, p[MAX][25];
int anc(int x, int y){
int pow = 0;
while(y && x){
if(y & 1){
if(!p[x][pow])
return 0;
x = p[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][0]);
int ok = 1, cnt = 0;
while(ok){
ok = 0;
for(int i = 1; i <= n; i++)
if(p[i][cnt] && p[p[i][cnt]][cnt]){
ok = 1;
p[i][cnt + 1] = p[p[i][cnt]][cnt];
}
cnt++;
}
for(int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
printf("%d\n", anc(x, y));
}
return 0;
}