Cod sursa(job #2196487)

Utilizator UnseenMarksmanDavid Catalin UnseenMarksman Data 19 aprilie 2018 15:57:40
Problema Stramosi Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.95 kb
#include <fstream>

using namespace std;

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

const int maxn = 250002;
const int lgn = 20;

int n, q, str[lgn][maxn], nod, level, lg[lgn]={0};

int main()
{
    fin>>n>>q;
    for(int i=1; i<=n; i++)
    {
        fin>>str[0][i];
    }

    for(int i=2; i<=18; i++) lg[i]=lg[i/2]+1;

    for(int j=1; j<=18; j++)
    {
        for(int i=1; i<=n; i++)
        {
            str[j][i]=str[j-1][str[j-1][i]];
        }
    }
    while(q--)
    {
        fin>>nod>>level;
        while(level>1)
        {
            int log=1;
            while(log*2<=level)
            {
                log=log*2;
            }
            nod=str[lg[log]][nod];
            level=level-log;
        }
        if(level==1)
        {
            fout<<str[0][nod];
        }
        else if(!level)
        {
            fout<<nod;
        }
        fout<<'\n';
    }
    return 0;
}