Cod sursa(job #2762007)

Utilizator bestman4111Tiberiu Niculae bestman4111 Data 5 iulie 2021 00:15:13
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.04 kb
#include<iostream>
#include<fstream>
using namespace std;

ifstream cit("stramosi.in");
ofstream afis("stramosi.out");

int N, M, stramos[20][250001], P, Q, nr_inm, putere, stram;

void log2(int x, int& put, int& inmult){
    while (put <= x){
        put = put * 2;
        inmult++;
    }
}

int main()
{
    cit>>N>>M;
    putere = 1;
    nr_inm = 0;
    log2(N, putere, nr_inm);
    for(int i = 1; i <= N; i++){
        cit>>stramos[0][i];
    }
    for(int i = 1; i <= nr_inm; i++){
        for(int j = 1; j <= N; j++){
            stramos[i][j] = stramos[i - 1][stramos[i - 1][j]];
        }
    }
    for(int i = 1; i <= M; i++){
        cit>>Q>>P;
        putere = 1;
        nr_inm = 0;
        log2(P, putere, nr_inm);
        stram = Q;
        while((P != 0) && (stram != 0)){
            if(putere <= P){
                stram = stramos[nr_inm][stram];
                P -= putere;
            }
            putere /= 2;
            nr_inm--;
        }
        afis<<stram<<"\n";
    }
    return 0;
}