Cod sursa(job #2862196)

Utilizator gripzStroescu Matei Alexandru gripz Data 4 martie 2022 23:47:00
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>

#define NMAX 100003
#define LOG 17

using namespace std;

int N, M;
int Fathers[NMAX][LOG], depth[NMAX];

void LCA(int a, int b) {
    if(depth[a] < depth[b]) {
        swap(a, b);
    }
    int i = LOG - 1;
    while(i >= 0) {
        if(depth[Fathers[a][i]] >= depth[b])
            a = Fathers[a][i];
        i--;
    }
    if(a == b) {
        printf("%d", a);
        return;
    } else {
        int i = LOG - 1;
        while(i >= 0)
        {
            if(Fathers[a][i] != Fathers[b][i]) {
                a = Fathers[a][i];
                b = Fathers[b][i];
            }
            i--;
        }
    }
    printf("%d\n", Fathers[a][0]);
}

int main()
{

    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);

    scanf("%d %d", &N, &M);

    Fathers[1][0] = -1;
    depth[1] = 1;

    for(int i = 2; i <= N; i++) {
        int f;
        scanf("%d", &f);
        Fathers[i][0] = f;
        depth[i] = depth[Fathers[i][0]] + 1;
    }

    for(int i = 1; i <= N; i++) {
        for(int j = 1; j < LOG; j++) {
            Fathers[i][j] = Fathers[Fathers[i][j - 1]][j - 1];
        }
    }

    for(int i = 1; i <= M; i++) {
        int a, b;
        scanf("%d %d", &a, &b);
        LCA(a, b);
    }

    return 0;
}