Cod sursa(job #3381032)

Utilizator Alexutu008Ionita Alexandru-Dumitru Alexutu008 Data 3 decembrie 2026 17:57:11
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;
// Binary lifting

const int maxn = 1e5 + 1, maxr = 20;
int t[maxr][maxn], lvl[maxn], lg[maxn]; // parintele nodului maxn la distanta 2^maxr

int anc(int x, int ord)
{
    int e = 0;
    while (ord)
    {
        if (ord & 1)
        {
            x = t[e][x];
        }
        ord >>= 1;
        ++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()
{
    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, q;
    cin >> n >> q;
    for (int i = 2; i <= n; ++i)
    {
        cin >> t[0][i];
        lvl[i] = lvl[t[0][i]] + 1;
    }

    for (int e = 1; e < maxr; ++e)
    {
        for (int i = 1; i <= n; ++i)
        {
            t[e][i] = t[e - 1][t[e - 1][i]];
        }
    }
    for (int i = 2; i < maxn; ++i)
        lg[i] = lg[i / 2] + 1;

    while (q--)
    {
        int x, y;
        cin >> x >> y;

        if (lvl[x] > lvl[y])
            swap(x, y);
        y = anc(y, lvl[y] - lvl[x]);
        if (x == y)
            cout << x << '\n';
        else
            cout << lca(x, y) << '\n';
    }

    return 0;
}