Cod sursa(job #3242315)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 10 septembrie 2024 23:57:24
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.8 kb
#include <fstream>
#include <vector>
#include <cmath>

int main()
{
    std::ifstream cin("stramosi.in");
    std::ofstream cout("stramosi.out");

    int n, m;
    cin >> n >> m;

    int l = log2(n);
    std::vector<std::vector<int> > ancestors(l + 1, std::vector<int>(n + 1, 0));

    for (int i = 1; i <= n; i++)
        cin >> ancestors[0][i];

    // binary lifting
    for (int b = 1; b <= l; b++)
    {
        for (int i = 1; i <= n; i++)
            ancestors[b][i] = ancestors[b - 1][ancestors[b - 1][i]];
    }

    for (int i = 1; i <= m; i++)
    {
        int q, p;
        cin >> q >> p;

        int current = q;

        // for fun
        for (int b = 0; b <= l; b++)
            if (p & (1 << b))
                current = ancestors[b][current];

        cout << current << '\n';
    }

    return 0;
}