Cod sursa(job #3331635)

Utilizator GliggyGligor Andrei Gliggy Data 29 decembrie 2025 15:24:20
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
// Copilot Rules:
// RULE: There shouldnt be any spaces in the code, except after commas.
// RULE: All variables in main should be declared globally, and can be used before they are defined.
// RULE: All open curly braces should be placed on the same line as the function or control structure they belong to, not on the line after.
#include <bits/stdc++.h>
#define N 100010
#define L 20
using namespace std;
ifstream fin("lca.in");   //strudel
ofstream fout("lca.out"); //lca
int n,i,q,a1,p,v1,v2,put,x,y;
int t[N],lvl[N],a[L][2*N],maxp[2*N],first[N];
vector<int> v[N];
void dfs(int n){
    a[0][++a1]=n;
    first[n]=a1;
    for(auto it:v[n]){
        lvl[it]=lvl[n]+1;
        dfs(it);
        a[0][++a1]=n;
    }
}
int main()
{
    fin>>n>>q;
    for(i=2;i<=n;i++) fin>>t[i],v[t[i]].push_back(i);
    dfs(1);
    for(p=1;p<L;p++){
        for(i=1;i<=a1;i++){
            v1=a[p-1][i];
            v2=i+(1<<(p-1));
            if(v2<=a1) v2=a[p-1][v2];
            else v2=v1;
            a[p][i]=(lvl[v1]>lvl[v2]?v2:v1);
        }
    }
    for(i=0,p=2,put=0;i<=a1;p*=2,put++){
        while(i<p&&i<=a1) maxp[i]=put,i++;
    }
    for(i=1;i<=q;i++){
        fin>>x>>y;
        x=first[x];
        y=first[y];
        if(x>y) swap(x,y);
        int pmax=maxp[y-x+1];
        v1=a[pmax][x];
        v2=a[pmax][y-(1<<pmax)+1];
        fout<<(lvl[v1]<lvl[v2]?v1:v2)<<'\n';
    }
    return 0;
}