Cod sursa(job #3250268)

Utilizator luca._.solosluca solos luca._.solos Data 19 octombrie 2024 20:28:13
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax=1e5+3, lg=20;
int sparse[nmax][lg], depth[nmax];
vector <int> v[nmax];

void dfs(int nod)
{
    for(auto i:v[nod])
    {
        sparse[i][0]=nod;
        for(int j=1; j<lg; j++)
        {
            sparse[i][j]=sparse[sparse[i][j-1]][j-1];
        }
        depth[i]=depth[nod]+1;
        dfs(i);
    }
}

int lca(int x, int y)
{
    if(depth[x]<depth[y]) swap(x, y);
    int dif=depth[x]-depth[y];
    for(int i=lg-1; i>=0; i--)
    {
        if((1<<i)&dif)
        {
            x=sparse[x][i];
        }
    }
    if(x==y) return x;
    for(int i=lg-1; i>=0; i--)
    {
        if(sparse[x][i]!=sparse[y][i])
        {
            x=sparse[x][i];
            y=sparse[y][i];
        }
    }
    return sparse[x][0];
}

int main()
{
    ifstream cin("lca.in");
    ofstream cout("lca.out");

    int n, q, a, b, x;
    cin>>n>>q;
    for(int i=2; i<=n; i++)
    {
        cin>>x;
        v[x].push_back(i);
    }
    dfs(1);
    while(q--)
    {
        cin>>a>>b;
        cout<<lca(a, b)<<'\n';
    }

    return 0;
}