Cod sursa(job #3231759)

Utilizator sstanciu44Stanciu Sebastian sstanciu44 Data 27 mai 2024 17:53:57
Problema Stramosi Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.8 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("stramosi.in");
ofstream g("stramosi.out");

int main() {
  long long n, m, i, j, q, p;
  f >> n >> m;
  int log_n = log2(n);
  vector<long long> depth(n + 1);
  vector<vector<long long>> ancestors(log_n + 1, vector<long long>(n + 1, 0));
  depth[0] = 0;
  for(i = 1; i <= n; ++i) {
    f >> ancestors[0][i];
    depth[i] = depth[ancestors[0][i]] + 1;
  }
  for(i = 1; i <= log_n; ++i)
    for(j = 1; j <= n; ++j)
      ancestors[i][j] = ancestors[i - 1][ancestors[i - 1][j]];
  for(i = 0; i < m; ++i) {
    f >> q >> p;
    if(p >= depth[q]) {
      cout << "0\n";
    } else {
      long long exp = 0;
      while(p) {
        if(p & 1)
          q = ancestors[exp][q];
        ++exp;
        p >>= 1;
      }
      cout << q << '\n';
    }
  }
  return 0;
}