Cod sursa(job #3308728)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 27 august 2025 18:35:17
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
//brut

#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, t[nmax], h[nmax];

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

int query (int x, int y)
{
    while (x != y)
    {
        if (h[x] > h[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);
    }
    build (1, 0);
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        fout << query (x, y) << '\n';
    }
    return 0;
}