Cod sursa(job #2879253)

Utilizator Mihai7218Bratu Mihai-Alexandru Mihai7218 Data 28 martie 2022 12:46:06
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.5 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, checkLin, anc[250001][21];
int main()
{
    fin.sync_with_stdio(false);
    fout.sync_with_stdio(false);
    fin >> n >> m;
    list <int> toUpd;
    toUpd.push_back(0);
    for (i = 1; i <= n; i++)
    {
        fin >> anc[i][0];
        if (anc[i][0] == i-1)
            checkLin++;
        toUpd.push_back(i);
    }
    if (checkLin == n)
    {
        for (j = 1; j <= m; j++)
        {
            fin >> q >> p;
            fout << (q-p)*(q>=p) << '\n';
        }
    }
    else
    {
        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";
        }
    }
    fin.close();
    fout.close();
    return 0;
}