Cod sursa(job #2910645)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 23 iunie 2022 11:26:51
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>

using namespace std;

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

const int max_size = 1e5 + 1, max_r = 17;

int t[max_r][max_size], nivel[max_size], lg[max_size], n;

void lvl (int x)
{
    if (nivel[x] != 0)
    {
        return;
    }
    lvl(t[0][x]);
    nivel[x] = 1 + nivel[t[0][x]];
}

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

int lca (int x, int y)
{
    int e = lg[nivel[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 q;
    in >> n >> q;
    for (int i = 2; i <= n; i++)
    {
        in >> t[0][i];
        lg[i] = lg[i / 2] + 1;
    }
    for (int e = 1; e < max_r; e++)
    {
        for (int i = 1; i <= n; i++)
        {
            t[e][i] = t[e - 1][t[e - 1][i]];
        }
    }
    nivel[1] = 1;
    for (int i = 2; i <= n; i++)
    {
        lvl(i);
    }
    while (q--)
    {
        int x, y;
        in >> x >> y;
        if (nivel[x] > nivel[y])
        {
            swap(x, y);
        }
        y = anc(y, nivel[y] - nivel[x]);
        if (y == x)
        {
            out << x << '\n';
        }
        else
        {
            out << lca(x, y) << '\n';
        }
    }
    in.close();
    out.close();
    return 0;
}