Cod sursa(job #3259226)

Utilizator andystarzSuna Andrei andystarz Data 25 noiembrie 2024 16:21:05
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>
#include <fstream>
using namespace std;
int papi[100005][20];
int height[100005];
int equalizer(int &a, int &b)
{
    if (a==b)
    return a;
    if (height[a]<height[b]) swap(a,b);
    int pas=19;
    while (pas>=0)
        {
        	if (height[a]-(1<<pas)>=height[b])
        	a=papi[a][pas];
            pas--;
        }
        return a;
}
int daddy(int a, int b)
{
    int pas=19;
    while (pas>=0)
    {
        if (papi[a][pas]!=papi[b][pas])
        {
            a=papi[a][pas];
            b=papi[b][pas];
        }
        pas--;
    }
    return papi[a][0];
}
int main()
{
	ifstream cin ("lca.in");
	ofstream cout ("lca.out");
    papi[1][0]=1;
    height[1]=1;
    ///fac structura cu fiecare nod care e taticul de putere 2^k
    int n, q, a, b;
    cin>>n>>q;
    for (int i=2; i<=n; i++)
    {
        cin>>papi[i][0] ;
        height[i] = 1 + height[papi[i][0]]        ;
    }
    for (int bit=1; bit<20; bit++)
    {
        for (int i=1; i<=n; i++)
        {
            papi[i][bit] = papi[papi[i][bit-1]][bit-1]   ;
            //cout<<papi[i][bit]<<" ";
        }
    }
    for (int i=1; i<=q; i++)
    {
        cin>>a>>b;
        //a=equalizer(a, b);
        equalizer(a, b);
        //cout<<a<<" "<<b<<"PL";
        if (a==b)cout<<a<<'\n';
        else
        {
            cout<<daddy(a,b)<<'\n';
        }
    }
}