Cod sursa(job #3308784)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 28 august 2025 00:05:24
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
//hld

#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, father[nmax], weight[nmax], lvl[nmax], heavy[nmax], top[nmax];

void dfs (int node)
{
    weight[node] = 1;
    lvl[node] = lvl[father[node]] + 1;
    for (auto it : g[node])
    {
        dfs (it);
        weight[node] += weight[it];
        if (weight[it] > weight[heavy[node]])
            heavy[node] = it;
    }
}

void hpd (int node, int tp)
{
    top[node] = tp;
    if (!heavy[node])
        return;
    hpd (heavy[node], tp);
    for (auto it : g[node])
    {
        if (it != heavy[node])
            hpd (it, it);
    }
}

int lca (int x, int y)
{
    if (x > y)
        swap (x, y);
    while (top[x] != top[y])
    {
        if (lvl[top[x]] > lvl[top[y]])
            x = father[top[x]];
        else
            y = father[top[y]];
    }
    if (lvl[x] < lvl[y])
        return x;
    return y;
}

int main ()
{
    fin >> n >> m;
    for (int i = 2; i <= n; i++)
    {
        fin >> father[i];
        g[father[i]].push_back (i);
    }
    father[1] = 1;
    dfs (1);
    hpd (1, 1);
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        fout << lca (x, y) << '\n';
    }
    return 0;
}