Cod sursa(job #3196763)

Utilizator adrian_zahariaZaharia Adrian adrian_zaharia Data 24 ianuarie 2024 19:04:23
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
#define FastIo() ios_base::sync_with_stdio(false), cin.tie(nullptr),cout.tie(nullptr);
using namespace  std;
const int nmax = 250005;
const int lg = 17;
int n,m;
int x,y;
int r[nmax][lg+1];
int nivel[nmax];
vector<int> G[nmax+1];

void dfs(int x,int niv){
    nivel[x]=niv;
    for(int y:G[x]){
        if(!nivel[y])
            dfs(y,niv+1);
    }
}
int lca(int x,int y){
    if(nivel[x]<nivel[y]) swap(x,y);

    for(int l=lg;l>=0;l--)
        if(nivel[x] - (1<<l) >= nivel[y])
            x = r[x][l];

    if(x==y) return x;

    for(int l = lg;l>=0;--l)
        if(nivel[x] - (1<<l)>=1 && r[x][l]!=r[y][l])
             x = r[x][l], y = r[y][l];

    return r[x][0];
}
int main(){
    ifstream fin("lca.in");
    ofstream fout("lca.out");
    FastIo();
    fin>>n>>m;
    for(int i=2;i<=n;i++) {
        fin>>r[i][0];
        G[r[i][0]].push_back(i);
    }

    dfs(1,1);
    for(int l = 1;(1<<l) <= n; l++)
        for(int i = 1; i <= n; i++)
            r[i][l]=r[r[i][l-1]][l-1];

    for(int i=1;i<=m;i++){
        fin>>x>>y;
        fout<<lca(x,y)<<'\n';
    }
    return 0;
}