Cod sursa(job #2121221)

Utilizator AlexandruLuchianov1Alex Luchianov AlexandruLuchianov1 Data 3 februarie 2018 14:28:55
Problema Stramosi Scor 60
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.77 kb
#include <iostream>
#include <fstream>

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

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