Cod sursa(job #3308730)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 27 august 2025 18:42:43
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
//sqrt

#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 1e5 + 5;

vector <int> g[nmax];

int n, m, h, t[nmax], lvl[nmax], parent[nmax];

void get_height (int nod, int x)
{
    lvl[nod] = x;
    for (auto it : g[nod])
        get_height (it, x + 1);
    h = max (h, x);
}

void build (int nod, int n, int x)
{
    parent[nod] = n;
    if (x % h == 0)
        n = nod;
    for (auto it : g[nod])
        build (it, n, x + 1);
}

int lca (int x, int y)
{
    while (parent[x] != parent[y])
    {
        if (lvl[x] > lvl[y])
            x = parent[x];
        else
            y = parent[y];
    }
    while (x != y)
    {
        if (lvl[x] > lvl[y])
            x = t[x];
        else
            y = t[y];
    }
    return x;
}

int main ()
{
    fin >> n >> m;
    for (int i = 2; i <= n; i++)
    {
        fin >> t[i];
        g[t[i]].push_back (i);
    }
    get_height (1, 0);
    h = floor (sqrt (h));
    build (1, 0, 0);
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        fout << lca (x, y) << '\n';
    }
    return 0;
}