Cod sursa(job #3227986)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 4 mai 2024 16:55:49
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.77 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("stramosi.in");
ofstream cout("stramosi.out");
const int nmax = 250000, lgmax = 17;
int n, m, t[nmax + 5][lgmax + 5], q, p, lg[nmax + 5];///  t[i][j] = al (1<<j) tata al lui i
int main()
{
  for (int i = 0; (1 << i) <= nmax; i++)
    lg[(1 << i)] = i;
  for (int i = 0; i <= nmax; i++)
    if (lg[i] == 0)
      lg[i] = lg[i - 1];
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
  {
    cin >> t[i][0];
    int j = 1;
    while (t[t[i][j - 1]][j - 1]){
      t[i][j] = t[t[i][j - 1]][j - 1];
      j++;
    }
  }
  for (int i = 1; i <= m; i++){
    cin >> q >> p;
    while (p and q){
      q = t[q][lg[p]];
      p -= (1 << lg[p]);
    }
    cout << q << "\n";
  }
  return 0;
}