Cod sursa(job #612370)

Utilizator crushackPopescu Silviu crushack Data 7 septembrie 2011 06:15:03
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.22 kb
#include <stdio.h>
#include <vector>
#define NMax 250010
#define LNMax 19
#define MAX_BUFF (1<<25)
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;
}