Cod sursa(job #1385523)

Utilizator laurenttlaurentiu pavel laurentt Data 12 martie 2015 00:29:00
Problema Stramosi Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.09 kb
#include<vector>
#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;

int main() {
  ifstream fin ("stramosi.in");
  ofstream fout("stramosi.out");

  int N,M;
  fin >> N >> M;
  vector<int> ancestors; ancestors.push_back(0);
  vector<pair<int, int> > tree; tree.push_back(make_pair(0,0));
  for(int i = 1; i <= N; ++i) {
    int x; fin >> x;
    ancestors.push_back(x);

    tree.push_back(make_pair(ancestors[i], ancestors[ancestors[i]]));

  }/*
  for(int i = 1; i <= N; ++i) {
    if(ancestors[i] == 0) {
      tree.push_back(make_pair(0,0));
    }
    else {
      tree.push_back(make_pair(ancestors[i], ancestors[ancestors[i]]));
    }
    }*/
  /*
  cout << "tree:";
  for(int i = 0; i < N; ++i)
  */
  for(int i = 0; i < M; ++i) {
    int P,Q; fin >> Q >> P;
    //--P;
    int anc = Q;
    //    cout << "Q:" << Q << " P:" << P << ": ";
    while(P > 0) {
      if(P >= 2) {
	anc = tree[anc].second;
	P -= 2;
      }
      else {
	anc = tree[anc].first;
	--P;
      }
      //      cout << anc << " ";
    }
    //    cout << "\n";
    fout << anc << "\n";
  }
  
  return 0;
}