Pagini recente » Cod sursa (job #3232475) | Cod sursa (job #2792402) | Cod sursa (job #529473) | Cod sursa (job #3215594) | Cod sursa (job #3273032)
/*
____ ___ _ ___ ____ _
/ ___| / _ \| | |_ _/ ___| / \
\___ \| | | | | | | | / _ \
___) | |_| | |___ | | |___ / ___ \
|____/ \___/|_____|___\____/_/ \_\
*/
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define int long long int
#define pii pair<int,int>
const int NMAX = 2e5+9;
const int MOD = 1e9+7;
int binpow(int n, int k)
{
if (k==0)
{
return 1;
}
int x=binpow(n,k/2)%MOD;
if (k%2==0)
{
return x*x%MOD;
}
else
{
return x*x%MOD*n%MOD;
}
}
ifstream fin ("stramosi.in");
ofstream fout ("stramosi.out");
#define cin fin
#define cout fout
const int LOG = 20;
int n,q,i,j,a,b;
vector<int>root,g[NMAX];
int parent[LOG][NMAX];
void dfs (int node, int parrent=0)
{
parent[0][node]=parrent;
for (auto it : g[node])
{
if (it==parrent)
{
continue;
}
dfs(it,node);
}
}
void gen_sparse ()
{
for (int i=1; i<LOG; i++)
{
for (int j=1; j<=n; j++)
{
if (parent[i-1][j])
{
parent[i][j]=parent[i-1][parent[i-1][j]];
}
}
}
}
int query (int node, int depth)
{
for (int i=LOG-1; i>=0; i--)
{
if (depth-(1<<i)>=0 && parent[i][node])
{
depth-=(1<<i);
node=parent[i][node];
}
}
if (depth)
{
return 0;
}
return node;
}
void run_case ()
{
cin>>n>>q;
for (i=1; i<=n; i++)
{
cin>>a;
if (a==0)
{
root.pb (i);
}
else
{
g[a].pb (i),g[i].pb (a);
}
}
for (auto it : root)
{
dfs(it);
}
gen_sparse();
while (q--)
{
cin>>a>>b;
cout<<query(a,b)<<'\n';
}
}
signed main ()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL),cout.tie (NULL);
int teste;
teste=1;
while (teste--)
{
run_case();
}
}