Pagini recente » Cod sursa (job #1352887) | Cod sursa (job #2927589) | Cod sursa (job #1407060) | Cod sursa (job #2590119) | Cod sursa (job #2641504)
#include <cstdio>
#include <cctype>
using namespace std;
FILE *fin = fopen( "stramosi.in", "r" ), *fout = fopen( "stramosi.out", "w" );
const int BufSz = (1 << 17);
int rpos = BufSz - 1;
char rbuf[BufSz];
static inline char readChar() {
if ( !(rpos = (rpos + 1) & (BufSz - 1)) ) {
fread( rbuf, 1, BufSz, fin );
}
return rbuf[rpos];
}
int readInt() {
int ch, res = 0;
while ( isspace( ch = readChar() ) );
do {
res = res * 10 + ch - '0';
} while ( isdigit( ch = readChar() ) );
return res;
}
const int MaxN = 250002;
const int MaxLog = 20;
int anc[MaxN][MaxLog]; //anc[i][p] = indicele stramosului 2^p al lui i
int log[MaxN];
int main() {
int n, q, p, i, lg;
fscanf( fin, "%d%d", &n, &q );
for ( i = 1; i <= n; ++i ) {
fscanf( fin, "%d", &anc[i][0] );
}
for ( p = 1; p <= MaxLog - 1; ++p ) {
for ( i = 1; i <= n; ++i ) {
anc[i][p] = anc[anc[i][p - 1]][p - 1];
}
}
for ( i = 2; i <= n; ++i ) {
log[i] = log[i / 2] + 1;
}
while ( q-- ) {
i = readInt();
p = readInt();
lg = log[p];
while ( p ) {
i = anc[i][lg];
p -= (1 << lg);
lg = log[p];
}
fprintf( fout, "%d\n", i );
}
fclose( fin );
fclose( fout );
return 0;
}