Cod sursa(job #2849467)

Utilizator Sho10Andrei Alexandru Sho10 Data 15 februarie 2022 10:47:44
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb

#include <bits/stdc++.h> //Andrei Alexandru a.k.a Sho10
#define ll long long
#define double long double
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#define all(a) (a).begin(), (a).end()
#define sz size
#define f first
#define s second
#define pb push_back
#define er erase
#define in insert
#define mp make_pair
#define pi pair
#define rc(s) return cout<<s,0
#define endl '\n'
#define mod 1000000007
#define PI 3.14159265359
#define MAXN 100005
#define INF 1000000005
#define LINF 1000000000000000005
#define CODE_START  ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
ll n,m,l[200005][25],h[200005],hh[200005];
vector<ll>g[200005];
void dfs(ll node,ll &p){
p++;
h[node]=p;
for(auto it : g[node]){
    dfs(it,p);
}
p++;
hh[node]=p;
}
ll lca(ll x,ll y){
if(x==y){
    return x;
}
if(h[x]<h[y]&&hh[x]>hh[y]){
    return x;
}
if(h[y]<h[x]&&hh[y]>hh[x]){
    return y;
}
while(h[l[x][0]]>h[y]||hh[l[x][0]]<hh[y]){
    for(ll j=1;j<=22;j++)
    {
        if(l[x][j]==0||(h[l[x][j]]<h[y]&&hh[l[x][j]]>h[y])){
            x=l[x][j-1];
            break;
        }
    }
}
return l[x][0];
}
int32_t main(){
CODE_START;
ifstream cin("lca.in");
ofstream cout("lca.out");
cin>>n>>m;
for(ll i=1;i<n;i++)
{
    ll x;
    cin>>x;
    g[x].pb(i+1);
    l[i+1][0]=x;
}
for(ll i=1;i<=22;i++)
{
    for(ll j=1;j<=n;j++)
    {
        l[j][i]=l[l[j][i-1]][i-1];
    }
}
ll x=0;
dfs(1,x);
while(m--){
    ll a,b;
    cin>>a>>b;
    cout<<lca(a,b)<<endl;
}
}