Pagini recente » Cod sursa (job #1642731) | Cod sursa (job #1242400) | Cod sursa (job #257917) | Cod sursa (job #677664) | Cod sursa (job #1385526)
#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 >= 8) {
anc = tree[tree[tree[anc].second].second].second;
P -= 8;
}
else 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;
}