Cod sursa(job #3243102)

Utilizator davidgeo123Georgescu David davidgeo123 Data 15 septembrie 2024 18:35:09
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX=100001;
vector<int> g[NMAX+1];

int tin[2*NMAX+5], timer=0;
pair<int, int> euler[2*NMAX+1];

void dfs(int nod, int depth)
{
    tin[nod]=++timer;
    euler[timer]={depth, nod};
    for(auto copil:g[nod])
    {
        dfs(copil, depth+1);
        ++timer;
        euler[timer]={depth, nod};
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);
    int n, q;
    cin>>n>>q;
    for(int i=2, x; i<=n; i++)
    {
        cin>>x;
        g[x].push_back(i);
    }
    dfs(1, 1);
    int m=timer;
    pair<int, int> st[25][m+1];
    for(int i=1; i<=m; i++)
        st[0][i]=euler[i];
    for(int k=1; k<25; k++)
        for(int i=1; i+(1<<k)-1<=m; i++)
            st[k][i]=min(st[k-1][i], st[k-1][i+(1<<k-1)]);
    int lg[m+1];
    lg[1]=0;
    for(int i=2; i<=m; i++)
        lg[i]=1+lg[i>>1];

    int l, r;
    while(q--)
    {
        cin>>l>>r;
        l=tin[l], r=tin[r];
        if(l>r)swap(l, r);
        int layer=lg[r-l+1];
        cout<<(min(st[layer][l], st[layer][r-(1<<layer)+1])).second<<'\n';
    }
    return 0;
}