Cod sursa(job #3307293)

Utilizator Victor5539Tanase Victor Victor5539 Data 19 august 2025 17:29:50
Problema Lowest Common Ancestor Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

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

const int MAX=1e5,MAXP=17;
int n,i,E[MAX+5],t[MAX+5],depth[MAX+5],node1,node2,q,nr,p_end[MAX+5],p_start[MAX+5];
bool viz[MAX+5];
vector <int> edge[MAX+5];

struct elem{
int node,depth;}r[MAXP+5][2*MAX+5];

void dfs(int node)
{
    r[0][++nr]={node,depth[node]};
    p_start[node]=nr;

    viz[node]=1;

    for (auto node2: edge[node])
    {
        if (!viz[node2])
        {
            depth[node2]=depth[node]+1;
            dfs(node2);
            r[0][++nr]={node,depth[node]};
        }
    }

}

int lca(int x, int y)
{
    int st=p_start[x],dr=p_start[y];

    if (st>dr)
        swap(st,dr);

    int len=dr-st+1,e=E[len];

    elem cand1=r[e][st],cand2=r[e][dr-(1<<e)+1];

    if (cand1.depth<cand2.depth)
        return cand1.node;
    else
        return cand2.node;
}

void precalc()
{
    for (i=2; i<=nr; i++)
    E[i]=E[i>>1]+1;

    for (int p=1; (1<<p)<=nr; p++)
    {
        for (i=1; i<=nr; i++)
        {
            r[p][i]=r[p-1][i];

            if (i+(1<<(p-1))<=nr)
            {
                if (r[p-1][i+(1<<(p-1))].depth<r[p-1][i].depth)
                    r[p][i]=r[p-1][i+(1<<(p-1))];
            }
        }
    }

}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(0); fout.tie(0);

    fin>>n>>q;

    for (i=2; i<=n; i++)
    {
        fin>>t[i];
        edge[i].push_back(t[i]);
        edge[t[i]].push_back(i);
    }

    dfs(1);
    precalc();

    while (q--)
    {
        fin>>node1>>node2;

        fout<<lca(node1,node2)<<'\n';
    }



    return 0;
}