Cod sursa(job #3296383)

Utilizator Mirc100Mircea Octavian Mirc100 Data 12 mai 2025 14:10:39
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <vector>

using namespace std;

const int NMAX = 1e5;
const char nl = '\n';
const int LOG = 18;

vector<int> v[NMAX + 1];
int depth[2 * NMAX + 1];
int euler[2 * NMAX + 1];
int log_bin[2 * NMAX + 1];
int first_pos[2 * NMAX + 1];
int sptbl[2 * NMAX + 5][LOG];
int cnt = 0;

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

int query(int l, int r) {
    int len = r - l + 1;
    int j = log_bin[len];

    if(depth[sptbl[l][j]] < depth[sptbl[r - (1 << j) + 1][j]]) {
        return euler[sptbl[l][j]];
    } else {
        return euler[sptbl[r - (1 << j) + 1][j]];
    }
}

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

    dfs(1, 0);

    log_bin[1] = 0;
    for(int i = 2; i <= cnt; ++i) {
        log_bin[i] = log_bin[i / 2] + 1;
    }

    for(int i = 0; i < cnt; ++i) {
        sptbl[i][0] = i;
    }

    for(int j = 1; j < LOG; ++j) {
        for(int i = 1; i + (1 << j) - 1 <= 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];
            }
        }
    }

    for(int i = 0 ; i < cnt; ++i) {
        cout << euler[i] << ' ';
    }

    while(q--) {
        int u, v;
        cin >> u >> v;
        int l = min(first_pos[u], first_pos[v]);
        int r = max(first_pos[u], first_pos[v]);
        cout << query(l, r) << nl;
    }
    return 0;
}