Cod sursa(job #3290746)

Utilizator mihai21681Maricutu Mihai Alexandru mihai21681 Data 31 martie 2025 19:28:12
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
// lca.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <vector>
#include <fstream>
using namespace std;
ifstream cin("lca.in");
ofstream cout("lca.out");
int n, q, x, y, K;
vector<int> G[100001];
int depth[200001], euler[200001], first[100001];
int LG[200001], r[24][200001];
void dfs(int nod, int h) {
    euler[++K] = nod;
    depth[K] = h;
    first[nod] = K;
    for (int i : G[nod]) {
        dfs(i, h + 1);
        euler[++K] = nod;
        depth[K] = h;
    }
}
void init_rmq() {
    for (int i = 2; i <= K; i++)
        LG[i] = 1 + LG[i >> 1];
    for (int i = 1; i <= K; i++)
        r[0][i] = i;
    for (int i = 1, l = 1; (1 << i) < K; i++, l <<= 1)
        for (int j = 1; j + l <= K; j++)
            if (depth[r[i - 1][j]] < depth[r[i - 1][j + l]])
                r[i][j] = r[i - 1][j];
            else r[i][j] = r[i - 1][j + l];
}
int lca(int x, int y) {
    int a = first[x], b = first[y];
    if (a > b) swap(a, b);
    int i = LG[b - a + 1];
    int rez = r[i][a];
    if (depth[rez] > depth[r[i][b - (1 << i) + 1]]) 
        rez = r[i][b - (1 << i) + 1];
    return euler[rez];
}
int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin >> n >> q;
    for (int i = 2; i <= n; i++) {
        cin >> x;
        G[x].push_back(i);
    }
    dfs(1, 0);
    init_rmq();
    while (q--) {
        cin >> x >> y;
        cout << lca(x, y) << '\n';
    }
    return 0;
}