Cod sursa(job #3288734)

Utilizator mihai_bosIancu Mihai mihai_bos Data 23 martie 2025 23:36:20
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream cin("lca.in");
ofstream cout("lca.out");

const int N = 100005;
const int LOG = 18;

vector<int> v[N], euler;
int nivel[N], first[N], rmq[LOG][2 * N], E[2 * N];

void dfs(int nod, int parent) {
    if (first[nod] == -1)
        first[nod] = euler.size();
    euler.push_back(nod);

    for (auto x : v[nod]) {
        if (x != parent) {
            nivel[x] = nivel[nod] + 1;
            dfs(x, nod);
            euler.push_back(nod);
        }
    }
}

int main() {
    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= n; ++i)
        first[i] = -1;

    for (int i = 2; i <= n; ++i) {
        int a;
        cin >> a;
        v[i].push_back(a);
        v[a].push_back(i);
    }

    nivel[1] = 0;
    dfs(1, 0);

    int eulerSize = euler.size();

    // Compute log base 2 for all values up to 2n
    E[1] = 0;
    for (int i = 2; i <= eulerSize; ++i)
        E[i] = E[i / 2] + 1;

    // Build RMQ base case
    for (int i = 0; i < eulerSize; ++i)
        rmq[0][i] = i; // store index in euler[]

    // Build sparse table
    for (int i = 1; (1 << i) <= eulerSize; ++i) {
        for (int j = 0; j + (1 << i) <= eulerSize; ++j) {
            int idx1 = rmq[i - 1][j];
            int idx2 = rmq[i - 1][j + (1 << (i - 1))];

            if (nivel[euler[idx1]] < nivel[euler[idx2]])
                rmq[i][j] = idx1;
            else
                rmq[i][j] = idx2;
        }
    }

    // Answer queries
    for (int i = 1; i <= m; ++i) {
        int a, b;
        cin >> a >> b;
        int l = first[a];
        int r = first[b];
        if (l > r) swap(l, r);

        int logLen = E[r - l + 1];
        int idx1 = rmq[logLen][l];
        int idx2 = rmq[logLen][r - (1 << logLen) + 1];

        int lca_idx;
        if (nivel[euler[idx1]] < nivel[euler[idx2]])
            lca_idx = idx1;
        else
            lca_idx = idx2;

        cout << euler[lca_idx] << '\n';
    }

    return 0;
}