Cod sursa(job #1363603)

Utilizator andreey_047Andrei Maxim andreey_047 Data 27 februarie 2015 08:47:38
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.8 kb
#include <iostream>
#include <cstdio>
#define nmax 250005
using namespace std;
int dp[25][nmax],n,q;
int main(){
    int i,j,p,x,k,b;
    freopen("stramosi.in","r",stdin);
    freopen("stramosi.out","w",stdout);
    scanf("%d%d",&n,&q);
    for(i=1;i<=n;i++)
        scanf("%d",&dp[0][i]);
    for(i=1;i<=20;i++)
     for(j=1;j<=n;j++)
       dp[i][j]=dp[i-1][dp[i-1][j]];
    for(i=1;i<=q;i++){
        scanf("%d%d",&p,&x);
      k=1;j=0;
      while(k<x){k*=2;j++;}
      if(k==x) cout<<dp[j][p]<<'\n';
      else{ b=dp[j-1][p];k-=x;
        while(k){
            x=1;
            j=0;
            while(x<k){x*=2;j++;}
            if(!j&&x!=k)j=1;
          if(x==k)b=dp[j][b];
           else b=dp[j-1][b];
         k-=x;
        }
        cout<<b<<'\n';
      }
    }
    return 0;
}