Cod sursa(job #3037496)

Utilizator begusMihnea begus Data 25 martie 2023 17:05:18
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

const int NMAX=1e5+1;
const int LOG=17;

int n, m, depth[NMAX], up[NMAX][LOG];
vector<int> children[NMAX];

void dfs(int s){
    for(auto u : children[s]){
        depth[u]=depth[s]+1;
        up[u][0]=s;
        for(int j=1; j<LOG; j++){
            up[u][j]=up[up[u][j-1]][j-1];
        }
        dfs(u);
    }
}

int lca(int a, int b){
    if(depth[a]<depth[b]) swap(a, b);
    int k=depth[a]-depth[b];
    for(int j=LOG-1; j>=0; j--){
        if(k & (1<<j))
            a=up[a][j];
    }
    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 >> m;
    for(int i=2; i<=n; i++){
        int x;
        fin >> x;
        children[x].push_back(i);
    }
    up[1][0]=1;
    dfs(1);
    while(m--){
        int a, b;
        fin >> a >> b;
        fout << lca(a, b) << "\n";
    }
}