Cod sursa(job #3176451)

Utilizator PescarusTanislav Luca Andrei Pescarus Data 27 noiembrie 2023 09:29:31
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>

using namespace std;
const int nmax = 100005;

int father[nmax][23], depth[nmax];
int n, m;


int adancime(int node){
    if(node == 0){
        return node;
    }
    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");
    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';
    }
}