Cod sursa(job #3297755)

Utilizator paulihno15Ciumandru Paul paulihno15 Data 23 mai 2025 18:26:33
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
#define NMAX 100000
#define LOG 18

using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

int n, m, x, a, b;
vector<int> arb[NMAX + 2];
int niv[NMAX + 2];
int up[NMAX + 2][LOG];

void DFS_binar(int nod, int par) {
    niv[nod] = niv[par] + 1;
    for (int vec : arb[nod]) {
        if (vec == par) {
            continue;
        }
        up[vec][0] = nod;
        for (int j = 1; j < LOG; j++) {
            up[vec][j] = up[up[vec][j - 1]][j - 1];
        }
        DFS_binar(vec, nod);
    }
}

int LCA(int x, int y) {
    if (niv[x] < niv[y]) {
        swap(x, y);
    }
    for (int i = LOG - 1; i >= 0; i--) {
        if (niv[x] - (1 << i) >= niv[y]) {
            x = up[x][i];
        }
    }
    if (x == y) {
        return x;
    }
    for (int i = LOG - 1; i >= 0; i--) {
        if (up[x][i] != up[y][i]) {
            x = up[x][i];
            y = up[y][i];
        }
    }
    return up[x][0];
}

int main() {
    ios_base::sync_with_stdio(false);
    fin.tie(NULL);
    fout.tie(NULL);

    fin >> n >> m;
    for (int i = 2; i <= n; i++) {
        fin >> x;
        arb[x].emplace_back(i);
        arb[i].emplace_back(x);
    }

    DFS_binar(1, 0);

    while (m--) {
        fin >> a >> b;
        fout << LCA(a, b) << '\n';
    }
    return 0;
}