Pagini recente » Cod sursa (job #198913) | Cod sursa (job #729539) | Cod sursa (job #1500255) | Cod sursa (job #1428105) | Cod sursa (job #612368)
Cod sursa(job #612368)
#include <stdio.h>
#include <vector>
#define NMax 250010
#define LNMax 19
#define MAX_BUFF (1<<17)
using namespace std;
const char IN[]="stramosi.in",OUT[]="stramosi.out";
int N,M;
int P[NMax][LNMax];
bool visit[NMax];
char s[MAX_BUFF] ;int spct;
vector<int> ad[NMax];
void dfs(int x)
{
int i;
visit[x]=true;
for (i=1;P[x][i]=P[P[x][i-1]][i-1];++i);
for (i=0;i<(int)ad[x].size();++i) if (!visit[ad[x][i]])
dfs(ad[x][i]);
}
inline int Query(int x,int y)
{
int step;
for (step=17;step>=0;--step)
if ( y>=(1<<step) )
x=P[x][step],y-=(1<<step);
return x;
}
inline int next()
{
int ret=0;
while ( s[spct] && (s[spct]<'0' || s[spct]>'9')) ++spct;
while ( s[spct]>='0' && s[spct]<='9' )
ret= ret*10+ s[spct]-'0',++spct;
return ret;
}
inline void nextline(){
fgets( s , MAX_BUFF , stdin);spct=0;
}
int main()
{
int i,x,y;
freopen(IN,"r",stdin);
scanf("%d%d\n",&N,&M);
nextline();
for (i=1;i<=N;++i)
x=next() , ad[x].push_back(i) , P[i][0]=x;
dfs(0);
freopen(OUT,"w",stdout);
while (M--)
{
scanf("%d%d",&x,&y);
printf("%d\n",Query(x,y));
}
fclose(stdout);
fclose(stdin);
return 0;
}