Cod sursa(job #3293342)

Utilizator nistor_dora_valentinaNistor Dora Valentina nistor_dora_valentina Data 11 aprilie 2025 15:03:36
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <bits/stdc++.h>

using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n, m, i, j, rmq[21][100005], depth[100005], x, y;
vector <int> v[100005];
void dfs(int nod, int par)
{
    depth[nod]=depth[par]+1;
    for(auto i: v[nod])
        if(i!=par)
            dfs(i, nod);
}
int lca(int x, int y)
{
    int i;
    if(depth[x]<=depth[y])
        swap(x, y);
    for(i=18; i>=0; i--)
        if(depth[x]-(1<<i)>=depth[y])
            x=rmq[i][x];
    if(x==y)
        return y;
    for(i=18; i>=0; i--)
        if(rmq[i][x] && rmq[i][x]!=rmq[i][y])
    {
        x=rmq[i][x];
        y=rmq[i][y];
    }
    return rmq[0][x];
}
int main()
{
    fin>>n>>m;
    for(i=2; i<=n; i++)
    {
        fin>>rmq[0][i];
        v[i].push_back(rmq[0][i]);
        v[rmq[0][i]].push_back(i);
    }
    for(i=1; i<=n; i++)
        for(j=1; j<=18; j++)
            rmq[j][i]=rmq[j-1][rmq[j-1][i]];
    dfs(1, -1);
    while(m--)
    {
        fin>>x>>y;
        fout<<lca(x, y)<<'\n';
    }
    return 0;
}