Cod sursa(job #3294819)

Utilizator Mirc100Mircea Octavian Mirc100 Data 29 aprilie 2025 00:16:52
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include<fstream>
#include<iostream>
#include<cmath>
using namespace std;

struct node{
    int valoare;
    node* next;
};
void adaugareInceput(node* &head,  int x)
{
    node* element=new node;
    element->valoare=x;
    ///element->next=NULL;
    element->next=head; //devine NULL daca head este NULL

    head=element;

}
const int NMAX=100005;
const int LMAX=18;

ifstream fin("lca.in");

int n, Q, a, b;
int nivel[NMAX << 1], tata[NMAX << 1],tata_anter[NMAX];  

node* G[NMAX];

void preprocesare_tata(int nod, int niv,int b) { 
    nivel[nod] = niv ;
    node *p=G[nod];

    if (niv%b==0)
        tata_anter[nod]=tata[nod];
    else
        tata_anter[nod]=tata_anter[tata[nod]];
    while(p){
        preprocesare_tata(p->valoare,niv+1,b);
        p=p->next;
    }
    /*for (node* p= G[nod]; p!=NULL; p=p->next) {
        parcurg(p->valoare, niv +1);
  
        k=k+1;
        euler[k] = nod;
        nivel[k] = niv ;
    }*/

}

int query(int a,int b){
    while(tata_anter[a]!=tata_anter[b])
        if(nivel[a]>nivel[b])
            a=tata_anter[a];
        else
            b=tata_anter[b];
            
    while(a!=b)
        if(nivel[a]>nivel[b])
            a=tata[a];
        else
            b=tata[b];
    return a;
    
}

    



int main() {
ofstream fout("lca.out");

    fin >> n >> Q;
    for (int i = 1; i<=n; i++) //liste de fii
        G[i]=   NULL;
    for (int i = 2; i<=n; i++) { //nodul 1 este radacina- restul muchiilor i, a=tata[i]
        fin >> a;
        tata[i]=a;
        adaugareInceput(G[a],i); //in lista lui a punem pe i - la inceput
    }
    int k=-1;
    
    tata_anter[1]=1;
    preprocesare_tata(1,0,log2(n));//k ult poz completata->lung e k+1

    
    
    for(int i=0;i<Q;i++){
        fin >> a >> b;
        fout << query(a, b) << "\n";
    }
    fout.close();
    return 0;
}