Cod sursa(job #3294159)

Utilizator CalinHanguCalinHangu CalinHangu Data 17 aprilie 2025 14:52:24
Problema Lowest Common Ancestor Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;
const int NMAX = 1e5;
const int LOG = 20;
const char nl = '\n';

vector<int> v[NMAX + 5];
int sptbl[NMAX + 5][LOG];
int bin_log[NMAX + 5];
int euler[NMAX], depth[NMAX];
int first[NMAX + 5];
int cnt = 0;

void dfs(int node, int dep) {
    euler[cnt] = node;
    depth[cnt] = dep;
    first[node] = cnt;
    cnt++;

    for (auto x: v[node]) {
        dfs(x, dep + 1);
        euler[cnt] = node;
        depth[cnt] = dep;
        cnt++;
    }
}

int query_RMQ(int l, int r) {
    int len = r - l + 1;
    int j = bin_log[len];
    if (depth[sptbl[l][j]] < depth[sptbl[r - (1 << j) + 1][j]]) {
        return sptbl[l][j];
    } else {
        return sptbl[r - (1 << j) + 1][j];
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

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

    int n, q;
    cin >> n >> q;
    bin_log[1] = 0;
    for (int i = 2; i <= n; ++i) {
        int x;
        cin >> x;
        v[x].push_back(i);
        bin_log[i] = bin_log[i / 2] + 1;
    }
    dfs(1, 0); //node 1 and depth 0

    // sparse table based on euler tour
    for (int i = 0; i < cnt; ++i) {
        sptbl[i][0] = i;
    }

    for (int j = 1; (1 << j) <= cnt; ++j) {
        for (int i = 0; i + (1 << j) <= cnt; ++i) {
            if (depth[sptbl[i][j - 1]] < depth[sptbl[i + (1 << (j - 1))][j - 1]]) {
                sptbl[i][j] = sptbl[i][j - 1];
            } else {
                sptbl[i][j] = sptbl[i + (1 << (j - 1))][j - 1];
            }
        }
    }

    while (q--) {
        int u, v;
        cin >> u >> v;

        int l = min(first[u], first[v]);
        int r = max(first[u], first[v]);
        int index = query_RMQ(l, r);

        cout << euler[index] << nl;
    }
    return 0;
}