Cod sursa(job #3247405)

Utilizator Giulian617Buzatu Giulian Giulian617 Data 7 octombrie 2024 16:12:11
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.85 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("stramosi.in");
ofstream g("stramosi.out");
const int NMAX = 250005, LOGMAX = 20;
int n, m, Q, P, ancestor[LOGMAX][NMAX];
/// ancestor[i][j] = the 2^i ancestor of j
void binary_lifting()
{
    for (int i = 1; i < LOGMAX; i++)
        for (int j = 1; j <= n; j++)
            ancestor[i][j] = ancestor[i - 1][ancestor[i - 1][j]];
}
int find_ancestor(int node, int no_ancestor)
{
    if (no_ancestor >= (1 << LOGMAX))
        return 0;
    for (int i = 0; i < LOGMAX; i++)
        if (no_ancestor & (1 << i))
            node = ancestor[i][node];
    return node;
}
int main()
{
    f >> n >> m;
    for (int i = 1; i <= n; i++)
        f >> ancestor[0][i]; /// parent of i
    binary_lifting();
    for (int i = 1; i <= m; i++)
    {
        f >> Q >> P;
        g << find_ancestor(Q, P) << '\n';
    }
    return 0;
}