Cod sursa(job #3153954)

Utilizator BlueLuca888Girbovan Robert Luca BlueLuca888 Data 2 octombrie 2023 13:08:51
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.95 kb
#include <bits/stdc++.h>
#pragma GCC optimize ("O3")
#pragma GCC target ("popcnt")

using namespace std;

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

const int MAX_N = 250000;
const int MAX_M = 300000;
int n, m, nod, dst, pw2;
int lg2[MAX_N + 5], ancestor[18][MAX_N + 5];

int main (){
    ios_base::sync_with_stdio(false);
    fin.tie(nullptr), fout.tie(nullptr);

    fin>>n>>m;
    for(int i=1; i<=n; i++)
        fin>>ancestor[0][i];

    lg2[0] = lg2[1] = 0;
    for(int i=2; i<=n; i++)
        lg2[i] = lg2[(i>>1)] + 1;

    for(int i=1; i<=lg2[n]; i++)
        for(int j=1; j<=n; j++)
            ancestor[i][j] = ancestor[i-1][ancestor[i-1][j]];

    while(m--){
        fin>>nod>>dst;

        pw2 = 0;
        while(dst != 0){
            if(dst & 1)
                nod = ancestor[pw2][nod];
            pw2++;
            dst >>= 1;
        }

        fout<<nod<<"\n";
    }
    return 0;
}