Cod sursa(job #3148523)

Utilizator bigmixerVictor Purice bigmixer Data 2 septembrie 2023 12:36:23
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include<bits/stdc++.h>

using namespace std;

const int nmax = 100005;

int n, m, par[nmax][17], timpul, tin[nmax], tout[nmax];
vector<int>copii[nmax];


void dfs(int s){
    tin[s] = ++timpul;
    for(auto it : copii[s]){
        dfs(it);
    }
    tout[s] = ++timpul;
}

bool este_stramos(int x, int y){
    return (tin[x] < tin[y] && tout[x] > tout[y]);
}

int find_ancestor(int x, int y){
    if(este_stramos(x, y)) return x;
    for(int j=16;j>=0;j--){
        if(!par[x][j] || este_stramos(par[x][j], y)){
            continue;
        }else{
            x = par[x][j];
        }
    }
    return par[x][0];
}

int main(){
    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);
    cin >> n >> m;
    for(int i=2;i<=n;i++){
        int x; cin >> x;
        par[i][0] = x;
        copii[x].push_back(i);
    }
    for(int j=1;j<=16;j++){
        for(int i=1;i<=n;i++){
            par[i][j] = par[par[i][j - 1]][j - 1];
        }
    }
    dfs(1);
    // for(int i=1;i<=n;i++){
    //     cout << tin[i] << ' ' << tout[i] << '\n';
    // }
    for(int i=1;i<=m;i++){
        int x, y;
        cin >> x >> y;
        cout << find_ancestor(x, y) << '\n';
    }
}