Cod sursa(job #3292134)

Utilizator camillaCamelia camilla Data 7 aprilie 2025 10:16:50
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>

using namespace std;

#define dim1 22
#define dim2 100001
ifstream fin("lca.in");
ofstream fout("lca.out");
struct nod
{
    int t,h=0;
};
vector<nod> v;
int dp[dim1][dim2];
void nivel_identic(int &a,int &b)
{
    bool schimb=false;
    if(v[a].h>v[b].h)
    {
        swap(a,b);
        schimb=true;
    }
    /// a e mai sus decat b ( a.h < b.h )
    /// trebuie sa il urcam pe b cu v[b].h-v[a].h
    int dif=v[b].h-v[a].h,nod,i;
    nod=b;
    i=20;
    while(dif>0)
    {
        while((1<<i)>dif)
        {
            i--;
        }
        dif-=(1<<i);
        nod=dp[i][nod];
    }
    b=nod;
    if(schimb==true)
        swap(a,b);
}
int stramos_comun(int a,int b)
{
    if(a==b)
        return a;
    ///Incercam sa ajungem la nivelul fix de sub stramosul cautat(fii lui)
    int i=20;
    while(i>=0)
    {
        if(dp[i][a]==dp[i][b])
            i--;
        else
        {
            a=dp[i][a];
            b=dp[i][b];
        }
    }
    return v[a].t;
}

int main()
{
    int n,m,x,k,y,j,i;
    fin>>n>>m;
    v.resize(n+1);
    for(x=2;x<=n;x++)
    {
        fin>>y;
        v[x].t=y;
        v[x].h=v[y].h+1;
        dp[0][x]=y;
    }
    k=log2(n);
    for(i=1;i<=k;i++)
    {
        for(j=1;j<=n;j++)
        {
            dp[i][j]=dp[i-1][dp[i-1][j]];
        }
    }
    for(i=0;i<m;i++)
    {
        fin>>x>>y;
        ///Daca nu sunt pe acelasi nivel , le aducem noi
        if(v[x].h!=v[y].h)
        {
            nivel_identic(x,y);
        }
        fout<<stramos_comun(x,y)<<'\n';
    }
    return 0;
}