Pagini recente » Cod sursa (job #1412943) | Cod sursa (job #2829728) | Cod sursa (job #2296683) | hc_round_9 | Cod sursa (job #1815976)
#include <bits/stdc++.h>
#define BUF_SIZE 1<<17
#define MAXN 250000
#define LOGN 18
int pos = BUF_SIZE;
char buf[BUF_SIZE];
FILE *fin;
inline char nextch(){
if(pos==BUF_SIZE) fread(buf, 1, BUF_SIZE, fin), pos = 0;
return buf[pos++];
}
inline int read(){
int x=0;
char ch=nextch();
while(!isdigit(ch)) ch=nextch();
while(isdigit(ch)){
x=10*x+ch-'0';
ch=nextch();
}
return x;
}
int lista[MAXN+1], next[MAXN+1], str[LOGN+1][MAXN+1];
inline int stramos(int x, int y){
for(int i=0; i<=LOGN; i++)
if(y&(1<<i))
x=str[i][x];
return x;
}
void dfs(int x){
int p=lista[x];
while(p){
dfs(p);
p=next[p];
}
}
int main(){
int n, q, x, y;
FILE *fout;
fin=fopen("stramosi.in", "r");
fout=fopen("stramosi.out", "w");
n=read();
q=read();
for(int i=1; i<=n; i++){
str[0][i]=read();
next[i]=lista[str[0][i]];
lista[str[0][i]]=i;
}
dfs(lista[0]);
for(int i=1; i<=LOGN; i++)
for(int j=1; j<=n; j++)
str[i][j]=str[i-1][str[i-1][j]];
for(int i=0; i<q; i++){
x=read();
y=read();
fprintf(fout, "%d\n", stramos(x, y));
}
fclose(fin);
fclose(fout);
return 0;
}