Cod sursa(job #3343929)

Utilizator Anul2024Anul2024 Anul2024 Data 28 februarie 2026 18:54:13
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream fin ("lca.in");
ofstream fout ("lca.out");
const int DIM = 100000;
int n, q, niv[DIM + 1], t[DIM + 1], p[DIM + 1];
vector <int> v[DIM + 1];
void read ()
{
    int x;
    fin >> n >> q;
    for (int i = 2; i <= n; i++)
    {
        fin >> x;
        v[x].push_back (i);
        t[i] = x;
    }
}
void dfs (int nod, int l)
{
    niv[nod] = l;
    int t1 = p[nod], t2 = p[t1];
    bool ok = (niv[nod] - niv[t1] == niv[t1] - niv[t2]);
    for (int i = 0; i < (int) v[nod].size (); i++)
    {
        int vecin = v[nod][i];
        if (ok)
            p[vecin] = t2;
        else
            p[vecin] = nod;
        dfs (vecin, l + 1);
    }
}
int get_node (int x, int y)
{
    if (niv[x] < niv[y])
        swap (x, y);
    int dif = niv[x] - niv[y];
    if (dif > 0)
    {
        while (niv[x] > niv[y])
        {
            if (niv[p[x]] > niv[y])
                x = p[x];
            else
                x = t[x];
        }
    }
    while (x != y)
    {
        if (p[x] != p[y])
        {
            x = p[x];
            y = p[y];
        }
        else
        {
            x = t[x];
            y = t[y];
        }
    }
    return x;
}
void solve ()
{
    int x, y;
    while (q--)
    {
        fin >> x >> y;
        int lca = get_node (x, y);
        fout << lca << "\n";
    }
}
int main()
{
    read ();
    dfs (1, 1);
    solve ();
    return 0;
}