Cod sursa(job #2879225)

Utilizator Mihai7218Bratu Mihai-Alexandru Mihai7218 Data 28 martie 2022 12:34:31
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.05 kb
#include <fstream>
#include <cmath>
#include <list>
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
int n, i, j, m, p, q, anc[250001][21];
int main()
{
    fin >> n >> m;
    list <int> toUpd;
    toUpd.push_back(0);
    for (i = 1; i <= n; i++)
    {
        fin >> anc[i][0];
        toUpd.push_back(i);
    }
    int sz = int(log2(n));
    for (j = 1; j <= sz; j++)
    {
        list<int>::iterator it = toUpd.begin();
        for (it++; it != toUpd.end(); it++)
        {
            anc[(*it)][j] = anc[anc[(*it)][j-1]][j-1];
            if (anc[(*it)][j] == 0)
            {
                list <int> :: iterator it2 = it;
                it2--;
                toUpd.erase(it);
                it = it2;
            }
        }
    }
    for (j = 1; j <= m; j++)
    {
        fin >> q >> p;
        int str = q;
        while (p > 0)
        {
            str = anc[str][int(log2(p))];
            p -= (1 << int(log2(p)));
        }
        fout << str << "\n";
    }
    return 0;
}