Cod sursa(job #2758992)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 14 iunie 2021 19:53:51
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 100003;
const int LOG = 17;
int n,m;
int depth[NMAX];
int up[NMAX][LOG+1];
vector<int>v[NMAX];

void dfs(int nod){
    for(int child:v[nod]){
        depth[child]=depth[nod]+1;
        up[child][0]=nod;
        for(int i=1;i<=LOG;i++)
            up[child][i]=up[up[child][i-1]][i-1];
        dfs(child);
    }
}
int get_lca(int x,int y){// O(log N) solution
    if(depth[x] < depth[y])swap(x,y);
    int k = depth[x] - depth[y];
    for(int j=LOG;j>=0;j--)
        if(k&(1<<j))
            x = up[x][j];
    if(x==y)return x;
    for(int i=LOG;i>=0;i--)
        if(up[x][i]!=up[y][i]){
            x = up[x][i];
            y = up[y][i];
        }
    return up[x][0];
}

int main(){
    freopen("lca.in","r",stdin);
    freopen("lca.out","w", stdout);
    scanf("%d %d",&n,&m);
    for(int i=1;i<n;i++){
        int x;
        scanf("%d",&x);
        v[x].push_back(i+1);
    }
    dfs(1);
    while(m--){
        int x,y;
        scanf("%d %d",&x,&y);
        printf("%d\n",get_lca(x,y) );

    }


    return 0;
}