Pagini recente » Cod sursa (job #1621437) | Cod sursa (job #49816) | Cod sursa (job #2811685) | Cod sursa (job #928644) | Cod sursa (job #2344203)
#include <bits/stdc++.h>
using namespace std;
#if 1
#define pv(x) std::cerr<<#x<<" = "<<(x)<<"; ";std::cerr.flush()
#define pn std::cerr<<std::endl
#else
#define pv(x)
#define pn
#endif
#ifdef INFOARENA
ifstream in("stramosi.in");
ofstream out("stramosi.out");
#else
#define in cin
#define out cout
#endif
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using pld = pair<ld, ld>;
#define pb push_back
const double PI = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862;
const int inf_int = 1e9 + 5;
const ll inf_ll = 1e18 + 5;
const int NMax = 25e4 + 5;
const int dx[] = {-1,0,0,+1}, dy[] = {0,-1,+1,0};
const double EPS = 1e-8;
int ancestor[NMax][20], lg[NMax];
int getAncestor(int node, int pth, int N) {
if (pth >= N) {
return 0;
}
for (int exp = lg[pth]; exp >= 0; --exp) {
if ((1<<exp) <= pth) {
node = ancestor[node][exp];
pth -= (1<<exp);
}
}
return node;
}
int main() {
cin.sync_with_stdio(false);
cin.tie(0);
int N,M;
in >> N >> M;
for (int i = 1; i <= N; ++i) {
int dad;
in >> dad;
ancestor[i][0] = dad;
lg[i] = lg[i>>1] + 1;
}
for (int exp = 1; (1<<exp) <= N; ++exp) {
for (int i = 1; i <= N; ++i) {
ancestor[i][exp] = ancestor[ ancestor[i][exp - 1] ][exp - 1];
}
}
for (int i = 1; i <= M; ++i) {
int q,p;
in >> q >> p;
out << getAncestor(q, p, N) << '\n';
}
return 0;
}