Cod sursa(job #2752672)

Utilizator blxqnAlina Voiculescu blxqn Data 18 mai 2021 21:35:21
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <math.h>

using namespace std;

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

int n, m, ancestors[50][250001];

void calculateAncestors()
{
    for (int i = 1; pow(2, i) <= n; i++)
        for (int j = 1; j <= n; j++)
            ancestors[i][j] = ancestors[i-1][ancestors[i-1][j]];
}

int searchAncestor(int pos, int noAncestors)
{
    int maxPow, ancestorP, index;

    ancestorP = pos;

    while (noAncestors != 0)
    {
        maxPow = 1;
        index = 0;
        while (maxPow * 2 <= noAncestors)
        {
            maxPow *= 2;
            index++;
        }
        ancestorP = ancestors[index][ancestorP];

        noAncestors -= maxPow;
    }
    return ancestorP;
}

int main()
{
    int p, q;
    fin>>n>>m;

    for(int j = 1; j <= n; j++)
        fin>>ancestors[0][j];

    calculateAncestors();

    for(int i = 1; i <= m; i++)
    {
        fin>>q>>p;
        fout<<searchAncestor(q, p)<<"\n";
    }

    return 0;
}