Cod sursa(job #3004511)

Utilizator pifaDumitru Andrei Denis pifa Data 16 martie 2023 13:08:31
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream in ("lca.in");
ofstream out ("lca.out");

const int max_size = 1e5 + 1, rmax = 20;

int lin[2 * max_size], poz[max_size], rmq[rmax][4 * max_size], v[2 * max_size], timp, lg[2 * max_size];
vector <int> mc[max_size];

void dfs (int nod, int nivel)
{
    timp++;
    lin[timp] = nod;
    poz[nod] = timp;
    v[nod] = nivel;
    for (auto f : mc[nod])
    {
        dfs(f, nivel + 1);
        lin[++timp] = nod;
    }
}

bool cmp (int x, int y)
{
    return v[x] < v[y];
}

int main ()
{
    int n, q;
    in >> n >> q;
    for (int i = 2; i <= n; i++)
    {
        int x;
        in >> x;
        mc[x].push_back(i);
    }
    dfs(1, 1);
    for (int i = 1; i <= timp; i++)
    {
        rmq[0][i] = lin[i];
        if (i > 1)
        {
            lg[i] = lg[i / 2] + 1;
        }
    }
    for (int e = 1; (1 << e) <= timp; e++)
    {
        for (int i = 1; i + (1 << (e - 1)) - 1 <= timp; i++)
        {
            rmq[e][i] = min(rmq[e - 1][i], rmq[e - 1][i + (1 << (e - 1))], cmp);
        }
    }
    while (q--)
    {
        int x, y;
        in >> x >> y;
        x = poz[x];
        y = poz[y];
        if (x > y)
        {
            swap(x, y);
        }
        int diff = y - x + 1, e = lg[diff];
        out << min(rmq[e][x], rmq[e][y - (1 << e) + 1], cmp) << '\n';
    }
    in.close();
    out.close();
    return 0;
}