Cod sursa(job #2924190)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 26 septembrie 2022 20:08:53
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>
#define INFILE "lca.in"
#define OUTFILE "lca.out"
#define DIM 100005
#define LOG 17

using namespace std;

ifstream f(INFILE);
ofstream g(OUTFILE);

int n, m;
int lvl[DIM], up[DIM][LOG + 1];
bitset <DIM> visited;
vector <int> edges[DIM];

void dfs(int node, int father) {

    lvl[node] = lvl[father] + 1;
    visited[node] = 1;

    for (auto child: edges[node]) {
        up[child][0] = node;
        for (int i = 1; i <= LOG; i++) {
            up[child][i] = up[up[child][i - 1]][i - 1];
        }

        dfs(child, node);
    }
}

int getLCA(int node1, int node2) {

    if (lvl[node2] > lvl[node1]) {
        swap(node1, node2);
    }

    int k = lvl[node1] - lvl[node2];
    for (int i = LOG; i >= 0; i--) {
        if (k & (1 << i)) {
            node1 = up[node1][i];
        }
    }

    if (node1 == node2) {
        return node1;
    }

    for (int i = LOG; i >= 0; i--) {
        if (up[node1][i] != up[node2][i]) {
            node1 = up[node1][i];
            node2 = up[node2][i];
        }
    }

    return up[node1][0];
}

int main() {

    f >> n >> m;

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

    dfs(1, 0);

    for (int i = 1; i <= m; i++) {
        int x, y;
        f >> x >> y;
        g << getLCA(x, y) << "\n";
    }

    return 0;
}