Cod sursa(job #3344005)

Utilizator bogdan1479Luca Bogdan Alexandru bogdan1479 Data 28 februarie 2026 23:34:21
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 1e5 + 1, LOGMAX = 20;

int n, m, cnt;

int t[LOGMAX][2 * NMAX], log2[2 * NMAX], ap[NMAX], niv[NMAX];
/// ap[i] = prima aparitie a nodului i in reprezentarea Euler

vector<int> G[NMAX];

void citire() {
    fin >> n >> m;

    for(int i = 1, x; i < n; ++i) {
        fin >> x;
        G[x].push_back(i + 1);
    }

    niv[1] = 1; /// putea fi si 0, dar asa imi place
}

void dfs(int x) {
    t[0][++cnt] = x;
    ap[x] = cnt;

    for(const auto& y : G[x]) {
        niv[y] = niv[x] + 1;
        dfs(y);
        t[0][++cnt] = x;
    }
}

void initLog() {
    log2[0] = -1;
    for(int i = 1; i <= cnt; ++i) {
        log2[i] = log2[i >> 1] + 1;
    }
}

void genRMQ() {
    initLog();

    for(int i = 1, lg = 2; lg <= cnt; ++i, lg <<= 1) {
        for(int j = 1; j + lg - 1 <= cnt; ++j) {
            int a = t[i - 1][j], b = t[i - 1][j + lg / 2];

            if(niv[a] < niv[b]) {
                t[i][j] = a;
            } else {
                t[i][j] = b;
            }
        }
    }
}

int query(int x, int y) {
    if(x > y) swap(x, y);

    int k = log2[y - x + 1], lg = (1 << k), a = t[k][x], b = t[k][y - lg + 1];

    if(niv[a] < niv[b]) {
        return a;
    } else {
        return b;
    }
}

void solutie() {
    int x, y;

    while(m--) {
        fin >> x >> y;
        fout << query(ap[x], ap[y]) << '\n';
    }
}

int main() {
    citire();
    dfs(1);
    genRMQ();
    solutie();

    return 0;
}