Cod sursa(job #3201565)

Utilizator paull122Paul Ion paull122 Data 9 februarie 2024 01:01:19
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

#define NMAX 100000
#define ll long long
#define MOD 666013
using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

struct nod
{
    int n,h;
};
vector<int> adj[NMAX+1];

nod rmq[21][2*NMAX+1];

int first[NMAX+1],cntEuler=0;
int n,q;
int e[2*NMAX+1];
void dfs(int i,int h)
{
    rmq[0][++cntEuler]={i,h};
    first[i] = cntEuler;

    for(int j : adj[i])
    {
        dfs(j,h+1);
        rmq[0][++cntEuler] = {i,h};
    }
}
int main()
{
    fin >> n >> q;
    for(int i=2;i<=n;i++)
    {
        int x;
        fin >> x;
        adj[x].push_back(i);
    }
    dfs(1,1);
    for(int i=1;(1<<i) <= cntEuler;i++)
    {
        for(int j=1;j<=cntEuler;j++)
        {
            nod left = rmq[i-1][j];
            nod right = rmq[i-1][min(j + (1 << (i-1)),cntEuler)];
            rmq[i][j] = left.h < right.h ? left : right;
        }
    }
    e[1]=0;
    for(int i=2;i<=cntEuler;i++)
    {
        e[i] = e[i/2] + 1;
    }
    while(q--)
    {
        int x,y;
        fin >> x >> y;
        x=first[x], y=first[y];
        if(x > y)
        {
            swap(x,y);
        }

        int len = e[y-x+1];
        nod left = rmq[len][x];
        nod right = rmq[len][y-(1<<len)+1];
        fout << (left.h < right.h ? left.n : right.n) << "\n";
    }
}