Cod sursa(job #1385528)

Utilizator laurenttlaurentiu pavel laurentt Data 12 martie 2015 00:35:23
Problema Stramosi Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.25 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));
  vector<int> numAnc; numAnc.push_back(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]]));
    numAnc.push_back(numAnc[ancestors[i]] + 1);
  }/*
  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;
    if(numAnc[Q] < P) {
      fout << "0\n";
    }
    else{
      while(P > 0) {
	if(P >= 4) {
	  anc = tree[tree[anc].second].second;
	  P -= 4;
	}
	else if(P >= 2) {
	  anc = tree[anc].second;
	  P -= 2;
	}
	else {
	  anc = tree[anc].first;
	  --P;
	}
	//      cout << anc << " ";
      }
      //    cout << "\n";
      fout << anc << "\n";
    }
  }
  
  return 0;
}