Cod sursa(job #2846496)

Utilizator Sho10Andrei Alexandru Sho10 Data 9 februarie 2022 11:46:56
Problema Lowest Common Ancestor Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h> //Andrei Alexandru a.k.a Sho
#define ll long long
#define double long double
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#define aint(a) (a).begin(), (a).end()
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define pi pair
#define rc(s) return cout<<s,0
#define endl '\n'
#define mod 998244353
#define PI 3.14159265359
#define INF 1000000005
#define LINF 1000000000000000005ll
#define CODE_START  ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
ll n,p[500005],lca[21][500005],in[500005],out[500005],t=0,q;
vector<ll>g[500005];
void dfs(ll node,ll par){
in[node]=++t;
for(auto it : g[node]){
        dfs(it,node);
}
out[node]=++t;
}
bool check(ll x,ll y){
return in[x]<=in[y]&&out[x]>=out[y];
}
ll lowesta(ll x,ll y){
if(check(x,y)){
    return x;
}
if(check(y,x)){
    return y;
}
if(in[y]>=in[x]&&in[y]<=out[x]){
    return x;
}
for(ll i=20;i>=0;i--)
{
    if(check(lca[i][x],y)==1&&check(y,lca[i][x])==1){
        x=lca[i][x];
    }
}
return lca[0][x];
}
int32_t main(){
CODE_START;
ifstream cin("lca.in");
ofstream cout("lca.out");
cin>>n>>q;
for(ll i=2;i<=n;i++)
{
    ll x;
    cin>>x;
    g[x].pb(i);
    lca[0][i]=x;
}
lca[0][1]=1;
for(ll i=1;i<=20;i++)
{
    for(ll j=1;j<=n;j++)
    {
        lca[i][j]=lca[lca[i][j-1]][j-1];
    }
}
dfs(1,0);
while(q--){
    ll x,y;
    cin>>x>>y;
    cout<<lowesta(x,y)<<endl;
}
}