Cod sursa(job #3143472)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 30 iulie 2023 15:29:58
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#define pb push_back
using namespace std;
using pii = pair<int,int>;

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

const int MAX = 1e5 + 1;

int n , q , v[MAX] , hn , x , y , lift[18][MAX] , depth[MAX];
vector <int> g[MAX];

void dfs( int x , int p ){

    depth[x] = depth[p]+1;

    lift[0][x] = p;

    for(int i = 1 ; i <= 17 ; i++){

        lift[i][x] = lift[i-1][lift[i-1][x]];
    }

    for(auto it : g[x]){

        if(it!=p){

            dfs(it,x);
        }
    }

}

int lca( int a , int b ){

    if(depth[a] > depth[b]){

        swap(a,b);
    }

    int val = depth[b]-depth[a];

    int i = 0;

    while(val){

        if(val%2) b = lift[i][b];

        val = val/2;

        i++;
    }

    if(a==b) return a;

    int pw = 17;

    while(pw>=0){

        if(lift[pw][a]!=lift[pw][b]){
            a = lift[pw][a];
            b = lift[pw][b];
        }
        pw--;
    }

    return lift[0][a];
}

signed main(){

    cin >> n >> q;

    for(int i = 2 ; i <= n ; i++){

        cin >> v[i];
        g[v[i]].pb(i);
    }

    dfs(1,0);

    int a , b;

    while(q--){

        cin >> a >> b; cout << lca(a,b) << '\n';
    }

    return 0;
}