Cod sursa(job #3245676)

Utilizator PitigoiOlteanEmanuelPitigoi Oltean Emanuel PitigoiOlteanEmanuel Data 30 septembrie 2024 06:44:50
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>
#include <algorithm>
#include <cmath>


using namespace std;

ifstream cin("lca.in");
ofstream cout("lca.out");


int  v[100][250005];
int nivel[100005];


int n;



int main()
{
 int q;
    cin>>n>>q;
    v[0][1]=0;
    for(int i=2;i<=n;i++)
    {
        cin>>v[0][i];
        nivel[i]=nivel[v[0][i]]+1;
    }
    int l=log2(n)+1;

    for(int i=1;i<=l;i++)
    {
       for(int k=1;k<=n;k++)
       {
           v[i][k]=v[i-1][v[i-1][k]];

       }
    }
     for(int i=0;i<=10;i++)
        {
            for(int k=1;k<=13;k++)
            {
                cout<<v[i][k]<<" ";
            }
            cout<<'\n';
        }


    for(int i=0;i<q;i++)
    {
        int a,b;
        cin>>a>>b;

        if(nivel[a]>nivel[b])
        {
            swap(a,b);
        }

        //a<b
        if(nivel[a]!=nivel[b])
        {
            int tata=nivel[b]-nivel[a]+1;

            int ans=0;
            int cur=b;
            for(int k=1;k<tata;k++)
            {
                b=v[0][b];
            }
        }
        //cout<<'\n';
        //cout<<a <<" "<<b<<'\n';
        int ans=0,t=nivel[b],rez=-1;
        for(int pas=(1<<l);pas>0;pas/=2)
        {
            if(pas<=t && v[pas][a]!=v[pas][b])
            {

                    ans=pas;
                    a=v[pas][a];
                    b=v[pas][b];


            cout<<a <<" "<<b<<'\n';

            }


        }
        if(a==b)
        {
            cout<<a;
        }
        else if(v[0][a]==v[0][b])
        {
            cout<<v[0][a];
        }
        else
        {
            a=v[0][a];
            cout<<v[0][a];
        }
       cout<<'\n';



    }







    return 0;
}