Cod sursa(job #2641503)

Utilizator euyoTukanul euyo Data 11 august 2020 17:58:53
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.21 kb
#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;

  fscanf( fin, "%d%d", &n, &q );
  for ( int i = 1; i <= n; ++i ) {
    fscanf( fin, "%d", &anc[i][0] );
  }
  for ( int p = 1; p <= MaxLog - 1; ++p ) {
    for	( int i = 1; i <= n; ++i ) {
      anc[i][p] = anc[anc[i][p - 1]][p - 1];
	}
  }
  for ( int i = 2; i <= n; ++i ) {
	log[i] = log[i / 2] + 1;
  }
  while ( q-- ) {
	int p, i;
	i = readInt();
	p = readInt();
    int lg = log[p];
    int b = i;
	while ( p ) {
	  b = anc[b][lg];
	  p -= (1 << lg);
	  lg = log[p];
	}
	fprintf( fout, "%d\n", b );
  }
  fclose( fin );
  fclose( fout );
  return 0;
}