Cod sursa(job #2974342)

Utilizator mihaistamatescuMihai Stamatescu mihaistamatescu Data 3 februarie 2023 21:15:50
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>

using namespace std;
constexpr int MAXN = 1e5 + 10;
constexpr int MAX_LOG = 17;
int pstart[MAXN];
int pend[MAXN];
int stramos[MAX_LOG + 2][MAXN];
int crt, n, q;
vector<int> L[MAXN];

void dfs(int nod) {
    pstart[nod] = ++crt;
    for (auto fiu: L[nod]) {
        dfs(fiu);
    }
    pend[nod] = ++crt;
}

inline bool isAncestor(int x, int y) {
    return pstart[x] <= pstart[y] && pend[x] >= pend[y];
}

void calcStramosi() {
    for (int p = 1; p <= MAX_LOG; p++) {
        for (int i = 1; i <= n; i++) {
            stramos[p][i] = stramos[p - 1][stramos[p - 1][i]];
        }
    }
}

int lca(int x, int y) {
    if (isAncestor(x, y)) {
        return x;
    }
    if (isAncestor(y, x)) {
        return y;
    }
    for (int p = MAX_LOG; p >= 0; p--) {
        int st = stramos[p][x];
        if (st != 0 && !isAncestor(st, y)) {
            x = st;
        }
    }
    return stramos[0][x];
}

int main() {
    ifstream fin("lca.in");
    ofstream fout("lca.out");
    fin >> n >> q;
    for (int i = 2; i <= n; i++) {
        fin >> stramos[0][i];
        L[stramos[0][i]].push_back(i);
    }
    calcStramosi();
    dfs(1);
    for (int i = 1; i <= q; i++) {
        int x, y;
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }
    return 0;
}