Pagini recente » Cod sursa (job #1443282) | Cod sursa (job #1683761) | Cod sursa (job #517693) | Cod sursa (job #1661602) | Cod sursa (job #2090296)
#include <bits/stdc++.h>
#define for0(i, n) for(int i = 0; i < n; i++)
#define for1(i, n) for(int i = 1; i <= n; i++)
#define pb push_back
#define mp make_pair
#define all(v) v.begin(), v.end()
#define V vector<int>
#define VP vector<pair<int, int> >
#define FASTIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
#ifdef _WIN32
#include <windows.h>
#define print(x) PRINT(x, #x)
template<typename T> inline const void PRINT(T VARIABLE, string NAME)
{
#ifndef ONLINE_JUDGE /// ONLINE_JUDGE IS DEFINED ON CODEFORCES
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 10);
cerr << NAME << " = " << VARIABLE;
SetConsoleTextAttribute(hConsole, 7);
cerr << '\n';
#endif
}
#else
#define print(x) 0
#endif
typedef long long ll;
typedef unsigned long long ull;
const ll INFLL = 2 * (ll)1e18 + 100;
const int INFINT = 2 * (int)1e9 + 100;
const double PI = atan(1) * 4;
const double EPS = 1e-12;
const int SEED = 1e3 + 7;
const int MOD = 1e9 + 7; /// careful here (7 or 9, 66.. etc)
const int NMAX = 250000 + 5;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
#define cin fin
#define cout fout
int n, q;
V tree[NMAX];
int parinte[NMAX][20], depth[NMAX], lg[NMAX], p[NMAX];
void dfs(int nod)
{
int temp = p[nod];
if(temp)
for0(i, 20)
{
parinte[nod][i] = temp;
if(temp == 0) break;
temp = parinte[temp][i];
}
for(auto i: tree[nod]) if(i != p[nod]) dfs(i);
}
V S;
int main()
{
cin >> n >> q;
for1(i, n)
{
int a;
cin >> a;
if(a == 0) S.pb(a);
tree[a].pb(i);
tree[i].pb(a);
p[i] = a;
}
for(auto i: S) dfs(i);
for(int i = 2; i < NMAX; i++) lg[i] = lg[i / 2] + 1;
while(q--)
{
int nod, p;
cin >> nod >> p;
if(nod > n || p > n)
{
cout << "0\n";
continue;
}
while(p)
{
nod = parinte[nod][lg[p]];
p -= (1 << lg[p]);
}
cout << nod << '\n';
}
return 0;
}