Cod sursa(job #3328464)

Utilizator andrei1232008nicolae andrei andrei1232008 Data 8 decembrie 2025 19:38:35
Problema Lowest Common Ancestor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <bits/stdc++.h>
#define victor vector
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n,q,i,x,y;

const int lim=100010;
int viz[lim],depth[lim],s[lim*4],sz,first[lim];
victor <int> v[lim],zh;
void dfs(int x,int step)
{
    viz[x]=1;
    depth[x]=step;
    zh.push_back(x);
    for(auto k:v[x])
    {
        if(viz[k]==0)
        {
            dfs(k,step+1);
            zh.push_back(x);
        }
    }
}
void update(int x,int value)
{
    x+=sz;
    while(x)
    {
        if(s[x]==INT_MAX)
            s[x]=value;
        else if(s[x]!=INT_MAX&&depth[value]<depth[s[x]])
            s[x]=value;
        x/=2;
    }
}

int query(int l,int r)
{
    l+=sz;
    r+=sz;
    int sol=INT_MAX,af=-1;
    while(l<=r)
    {
        if(l%2==1)
        {
            if(s[l]!=INT_MAX&&depth[s[l]]<sol)
            {
                sol=depth[s[l]];
                af=s[l];
            }
        }
        if(r%2==0)
        {
            if(s[r]!=INT_MAX&&depth[s[r]]<sol)
            {
                sol=depth[s[r]];
                af=s[r];
            }
        }
        l=(l+1)/2;
        r=(r-1)/2;
    }
    return af;
}
int lca(int x,int y)
{
    int rx=first[x];
    int ry=first[y];

    if(rx>ry)
    {
        swap(rx,ry);
    }

    return query(rx,ry);
}
int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(NULL);fout.tie(NULL);

    fin>>n>>q;
    for(i=1;i<=n-1;i++)
    {
        fin>>x;
        v[x].push_back(i+1);
    }
    dfs(1,0);
    for(i=1;i<=n;i++)
        first[i]=-1;
    for(auto x=0;x<zh.size();x++)
    {
        if(first[zh[x]]==-1){first[zh[x]]=x;}
    }
    sz=1;
    while(sz<(int)zh.size())sz<<=1;
    for(i=0;i<2*sz;i++)
        s[i]=INT_MAX;
    for(i=0;i<zh.size();i++)
    {
        update(i,zh[i]);
    }
    while(q--)
    {
        fin>>x>>y;
        fout<<lca(x,y)<<'\n';
    }
    return 0;
}