Cod sursa(job #2401666)

Utilizator soverysourSebastian soverysour Data 9 aprilie 2019 21:47:10
Problema Stramosi Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.7 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;

int main()
{
  ifstream f{"stramosi.in"};
  ofstream g{"stramosi.out"};

  int n, q;
  f >> n >> q;

  vector<int> fathers;

  int aux;
  for ( int i = 0; i < n; i++ ) {
    f >> aux;
    aux--;

    fathers.push_back(aux);
  }

  vector<vector<int>> dp;
  for ( int i = 0; i < n; i++ ) {
    dp.push_back(vector<int>{});

    if (fathers[i] != -1 ) {
      int current_ancestor = fathers[i];
      dp[i].push_back(current_ancestor);

      uint rank = 0;
      while ( current_ancestor != -1 ) {
        if ( dp[current_ancestor].size() <= rank ) {
          break;
        }

        dp[i].push_back(dp[current_ancestor][rank]);
        current_ancestor = dp[current_ancestor].size() <= rank + 1 ? -1 : dp[current_ancestor][rank + 1];
        rank++;
      }
    }
  }

  /*
  for ( auto y : dp ) {
    cout << "Size: " << y.size() << endl;
    for (auto e : y ) {
      cout << e << ',';
    }

    cout << endl;
  }
  */

  uint node, nth;
  for ( int i = 0; i < q; i++ ) {
    f >> node >> nth;

    node--;

    if ( dp[node].size() == 0 ) {
      cout << 0 << endl;
    }
    else {
      while (true) {
        uint total_size = dp[node].size(), node_index = 0, current = 1;

        while (current * 2 <= nth && node_index < total_size) {
          current *= 2;
          node_index++;
        }

        if ( nth / 2 + 1 > current || node_index == dp[node].size() ) {
          cout << 0 << endl;
          break;
        }

        if ( current == nth ) {
          cout << dp[node][node_index] + 1 << endl;
          break;
        }

        node = dp[node][node_index];
        nth -= current;
      }
    }
  }

  return 0;
}