Cod sursa(job #2973343)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 31 ianuarie 2023 19:48:55
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1 kb
#include <fstream>

using namespace std;

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

const int DIM = 250010;
const int LOG = 20;

int n, m, x, k;
int father[DIM], ancestors[LOG][DIM];

void calculateAncestors() {
    for (int node = 1; node <= n; node++)
        ancestors[0][node] = father[node];

    for (int pow = 1; pow < LOG; pow++)
        for (int node = 1; node <= n; node++)
            ancestors[pow][node] = ancestors[pow - 1][ancestors[pow - 1][node]];
}

int findAncestor(int node, int cnt) {
    int ancestor = 0;
    for (int pow = LOG - 1; pow >= 0 && cnt > 0; pow--) {
        if (cnt >= (1 << pow)) {
            ancestor = ancestors[pow][node];
            node = ancestor;
            cnt -= (1 << pow);
        }
    }
    return ancestor;
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= n; i++)
        fin >> father[i];

    calculateAncestors();

    for (int i = 1; i <= m; i++) {
        fin >> x >> k;
        fout << findAncestor(x, k) << '\n';
    }

    return 0;
}