Cod sursa(job #1559725)

Utilizator eu3neuomManghiuc Teodor-Florin eu3neuom Data 31 decembrie 2015 14:55:12
Problema Stramosi Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.16 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("stramosi.in");
ofstream fout("stramosi.out");

const int NMax = 250005;
const int BMax = 1e4 + 5;
const int O = 65;

int v[O][NMax];

int pos = BMax - 1;
char Buffer[BMax];
inline void Read(int &x){
    while(!isdigit(Buffer[pos])){
        if(++pos == BMax){
            fin.read(Buffer, BMax);
            pos = 0;
        }
    }
    x = 0;
    while(isdigit(Buffer[pos])){
        x = x * 10 + (Buffer[pos] - '0');
        if(++pos == BMax){
            fin.read(Buffer, BMax);
            pos = 0;
        }
    }
}

int main(){
    int n, t, q, p;
    Read(n); Read(t);
    for(int i = 1; i <= n; i++) Read(v[1][i]);
    for(int i = 1; i <= n; i++){
        for(int j = 2; j < O; j++){
            v[j][i] = v[1][v[j - 1][i]];
            if(v[j][i] == 0) break;
        }
    }
    while(t--){
        Read(q); Read(p);
        while(p > 0 && q != 0){
            if(p > O - 1){
                q = v[O - 1][q];
            } else {
                q = v[p][q];
            }
            p -= O - 1;
        }
        fout << q << "\n";
    }
    return 0;
}