Pagini recente » Cod sursa (job #797807) | Cod sursa (job #1528036) | Cod sursa (job #1508638) | Cod sursa (job #2466931) | Cod sursa (job #2283105)
#include <bits/stdc++.h>
using namespace std;
ifstream in("stramosi.in");
ofstream out("stramosi.out");
vector< vector< int > > stramos;
int main() {
ios::sync_with_stdio(false); in.tie(0); out.tie(0);
int n, m; in >> n >> m;
stramos.resize(n + 1, vector< int >(20));
for(int i = 1; i <= n; ++i) {
int s; in >> s;
if(s == 0) {
stramos[i][0] = -1;
} else {
stramos[i][0] = s;
}
}
for(int j = 1; j < 18; ++j) {
for(int i = 1; i <= n; ++i) {
if(stramos[i][j - 1] != -1) {
stramos[i][j] = stramos[stramos[i][j - 1]][j - 1];
} else {
stramos[i][j] = -1;
}
}
}
for(int i = 1; i <= m; ++i) {
int q, p; in >> q >> p;
int tempQ = q, tempP = p;
for(int k = 20; k >= 0 && tempQ >= 1 && tempP != 0; --k) {
if((1 << k) > tempP) {
continue;
} else {
tempQ = stramos[tempQ][k];
tempP -= (1 << k);
}
}
if(tempQ < 1 || tempQ == -1) {
out << "0\n";
} else {
out << tempQ << "\n";
}
}
in.close(); out.close();
return 0;
}