Cod sursa(job #2121225)

Utilizator AlexandruLuchianov1Alex Luchianov AlexandruLuchianov1 Data 3 februarie 2018 14:31:43
Problema Stramosi Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.78 kb
#include <iostream>
#include <fstream>

using namespace std;
ifstream in ("stramosi.in");
ofstream out ("stramosi.out");
int const nmax = 250000;
int const lgmax = 18;
int lg[5 + nmax];
int far[5 + nmax][5 + lgmax];
int n;

void computefar(){
  for(int h = 1 ; h <= lgmax ;h++){
    for(int i = 1 ; i <= n ;i++){
      int node = far[i][h - 1];
      far[i][h] = far[node][h - 1];
    }
  }
}
int query(int node ,int p){
  while(0 < p && 0 < node){
    int h = lg[p];
    p -= (1 << h);
    node = far[node][h];
  }
  return node;
}
int main()
{
  int k;
  in >> n >> k;
  for(int i = 1 ; i <= n ;i++){
    in >> far[i][0];
  }
  computefar();
  for(int i = 1 ; i <= k ;i++){
    int a , b;
    in >> a >> b;
    out << query(a , b) << '\n';
  }
  return 0;
}