Cod sursa(job #2982350)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 20 februarie 2023 00:21:41
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <fstream>
#include <vector>
#define DIM 100005
#define LOG 18

using namespace std;

ifstream f("lca.in");
ofstream g("lca.out");

int n, q;
int lvl[DIM], up[DIM][LOG];
vector<int> edges[DIM];

void dfs(int node, int father) {
    lvl[node] = lvl[father] + 1;
    for (auto x: edges[node]) {
        up[x][0] = node;
        for (int i = 1; i < LOG; i++) {
            up[x][i] = up[up[x][i - 1]][i - 1];
        }
        dfs(x, node);
    }
}

int lca(int a, int b) {
    if (lvl[a] > lvl[b]) {
        swap(a, b);
    }

    int k = lvl[b] - lvl[a];
    for (int i = 0; i < LOG; i++) {
        if (k & (1 << i)) {
            b = up[b][i];
        }
    }

    if (a == b) {
        return a;
    }

    for (int i = LOG - 1; i >= 0; i--) {
        if (up[a][i] != up[b][i]) {
            a = up[a][i];
            b = up[b][i];
        }
    }

    return up[a][0];
}

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

    dfs(1, 0);

    for (; q--;) {
        int x, y;
        f >> x >> y;
        g << lca(x, y) << "\n";
    }

    return 0;
}