Cod sursa(job #1253273)

Utilizator atatomirTatomir Alex atatomir Data 1 noiembrie 2014 00:06:52
Problema Stramosi Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.05 kb
#include <iostream>
#include <cstdio>

using namespace std;

#define maxN 250005
#define maxLog 25
#define maxLLog 20

long n,m,i,j,q,p,tmp;
long dp[maxN][maxLog];
bool util;

char s[250000*6+5];

int main()
{
    freopen("stramosi.in","r",stdin);
    freopen("stramosi.out","w",stdout);

    //scanf("%ld %ld\n",&n,&m);
    cin >> n >> m;
    for(i=1;i<=n;i++) //scanf("%ld",&dp[i][0]);
                        cin >> dp[i][0];
    for(j=1;j<=maxLLog;j++){
        util = false;
        for(i=1;i<=n;i++){
            if(!dp[dp[i][j-1]][j-1]) continue;
            dp[i][j] = dp[dp[i][j-1]][j-1];
            util = true;
        }
        if(!util) break;
    }

    for(;m;m--){
        //scanf("%ld %ld",&q,&p);
        cin >> q >> p;
        i = 0; tmp = 1;
        while(tmp << 1 <= p) tmp <<= 1,i++;
        while(i>=0){
            if(p&tmp) q = dp[q][i];
            tmp >>= 1;
            i--;

            if(!q) break;
        }
        //printf("%ld\n",q);
        cout << q << '\n';
    }

    return 0;
}