Cod sursa(job #3346087)

Utilizator CheeseEaterHackRoman Alex CheeseEaterHack Data 12 martie 2026 15:22:08
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");

int up[100001][20], depth[100001];
const int LOG=20; //ajunge pt 1e6
vector<int> graf[100001];
int n, q, x, y;

void dfs(int nod, int parinte)
{
    up[nod][0]=parinte;
    for (int j=1; j< LOG; j++)
    {
        up[nod][j]=up[ up[nod][j-1] ][j-1];
    }
    for (auto u: graf[nod])
    {
        if (u==parinte) continue;
        depth[u]=depth[nod]+1;
        dfs(u, nod);
    }
}

int lift(int a, int k)
{
    for (int j=0; j<LOG; j++)
    {
        if (k&(1<<j))
        {
            a=up[a][j];
        }
    }
    return a;
}

int lcaquery(int a, int b)
{
    if (depth[a]<depth[b])
    {
        swap(a, b);
    }
    //acumaducem pe a la aceeasi adancime cu b
    a=lift(a, depth[a]-depth[b]);
    if (a==b)
    {
        return a;
    }
    for (int j=LOG-1; j>=0; j--)
    {
        if (up[a][j]!=up[b][j])
        {
            a=up[a][j];
            b=up[b][j];
        }
    }
    return up[a][0];
}

int main()
{
    fin>>n>>q;
    for (int i=2; i<=n; i++)
    {
        fin>>x;
        graf[x].push_back(i);
        graf[i].push_back(x);
    }
    depth[1]=1;
    dfs(1, 0);
    for (int i=1; i<=q; i++)
    {
        fin>>x>>y;
        fout<<lcaquery(x, y)<<'\n';
    }

    return 0;
}