Cod sursa(job #3173593)

Utilizator PescarusTanislav Luca Andrei Pescarus Data 23 noiembrie 2023 11:47:54
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <iostream>
using namespace std;
const int nmax = 100005;
int father[nmax][25], Log2[nmax];
int depth[nmax];
int n, m;

int adancime(int node){
    if(node == 0){
        return 0;
    }
    if(depth[node] == 0){
        depth[node] = adancime(father[node][0]) + 1;
    }
    return depth[node];
}

int lca(int a, int b){
    if(adancime(a) < adancime(b)){
        swap(a, b);
    }
    int dif = depth[a] - depth[b];

    for(int p = 20; p >= 0; p--){
        if((dif & (1 << p))){
            a = father[a][p];
        }
    }
    if(a == b){
        return a;
    }
    for(int p = 20; p >= 0; p--){
        if(father[a][p] != father[b][p]){
            a = father[a][p];
            b = father[b][p];
        }
    }
    return father[a][0];

}
int main(){
    ifstream f("lca.in");
    ofstream g("lca.out");
    Log2[1] = 0;
    for(int i = 1;i <= nmax; i++){
        Log2[i] = Log2[i / 2] + 1;
    }

    //precalculam
    f >> n >> m;
    for(int i = 2; i <= n; i++){
        f >> father[i][0];
    }
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= 20; j++){
            father[i][j] = father[father[i][j - 1]][j - 1];
        }
    }
    
    while(m--){
        int u, v;
        f >> u >> v;   
        g << lca(u, v) << '\n';
    }
}