Cod sursa(job #3041034)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 30 martie 2023 20:35:42
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
/// Binary Lifting
#include <fstream>
#include <vector>

using namespace std;

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

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

int t[rmax][max_size], lvl[max_size], lg[max_size];
vector <int> mc[max_size];

void dfs (int nod, int par)
{
    lvl[nod] = lvl[par] + 1;
    t[0][nod] = par;
    for (auto f : mc[nod])
    {
        dfs(f, nod);
    }
}

int anc (int x, int ord)
{
    int e = 0;
    while (ord > 0)
    {
        if (ord % 2 == 1)
        {
            x = t[e][x];
        }
        ord /= 2;
        e++;
    }
    return x;
}

int lca (int x, int y)
{
    int e = lg[lvl[x]];
    while (e >= 0)
    {
        if (t[e][x] != t[e][y])
        {
            x = t[e][x];
            y = t[e][y];
        }
        e--;
    }
    return t[0][x];
}

int main ()
{
    int n, q;
    in >> n >> q;
    for (int i = 2; i <= n; i++)
    {
        int x;
        in >> x;
        mc[x].push_back(i);
        lg[i] = lg[i / 2] + 1;
    }
    dfs(1, 0);
    for (int e = 1; e < rmax; e++)
    {
        for (int i = 1; i <= n; i++)
        {
            t[e][i] = t[e - 1][t[e - 1][i]];
        }
    }
    while (q--)
    {
        int x, y;
        in >> x >> y;
        if (lvl[x] > lvl[y])
        {
            swap(x, y);
        }
        y = anc(y, lvl[y] - lvl[x]);
        if (x == y)
        {
            out << x << '\n';
        }
        else
        {
            out << lca(x, y) << '\n';
        }
    }
    in.close();
    out.close();
    return 0;
}