Cod sursa(job #3282311)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 4 martie 2025 23:16:39
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#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[nmax], dp[20][nmax];

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

int lca (int x, int y)
{
    if (h[x]<h[y])
        swap(x,y);
    int k=h[x]-h[y];
    for (int i=0; i<20; i++)
    {
        if ((1<<i)&k)
            x=dp[i][x];
    }
    if (x==y)
        return x;
    for (int i=19; i>=0; i--)
    {
        if (dp[i][x]!=dp[i][y])
        {
            x=dp[i][x];
            y=dp[i][y];
        }
    }

    return dp[0][x];
}

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