Cod sursa(job #2810446)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 29 noiembrie 2021 14:59:44
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

#pragma GCC optimize ("Ofast")

const int maxN = 255005, maxLg = 19;
int n, nq;
int s[maxN][maxLg + 5];

int main()
{
    ios::sync_with_stdio(false);
    fin >> n >> nq;
    for(int i = 1; i <= n; i++)
    {
        int t;
        fin >> t;
        s[i][0] = t;
    }
    for(int i = 1; i <= maxLg; i++)
        for(int nod = 1; nod <= n; nod++)
            s[nod][i] = s[s[nod][i - 1]][i - 1];
    for(int i = 1; i <= nq; i++)
    {
        int nod, nr, pow = 0;
        fin >> nod >> nr;
        if(nr == 1)
        {
            fout << s[nod][0] << '\n';
            continue;
        }
        while((1 << pow) <= nr)
            pow++;
        while(pow >= 0)
        {
            if(((1 << pow) & nr))
                nod = s[nod][pow];
            pow--;
        }
        fout << nod << '\n';
    }
    return 0;
}