Cod sursa(job #2604831)

Utilizator copanelTudor Roman copanel Data 23 aprilie 2020 16:50:15
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <fstream>
#include <vector>

struct node {
    int parent;
    int in, out;
    std::vector<int> children;
} nodes[100001];
int dp[17][100001]; // dp[i][j] este al 2^i-lea stramos al nodului j
                    // dp[0][j] este deci parintele lui j

void dfs(int node) {
    static int timp = 0;

    nodes[node].in = ++timp;
    for (const int child_id : nodes[node].children) {
        const auto& child = nodes[child_id];
        if (child.in == 0) {
            dfs(child_id);
        }
    }
    nodes[node].out = ++timp;
}

void gen_dp(int n) {
    for (int i = 1; (1 << i) <= n; i++) {
        for (int j = 1; j <= n; j++) {
            dp[i][j] = dp[i - 1][dp[i - 1][j]];
        }
    }
}

int lca(int n, int a, int b) {
    // caz particular: a este deja stramosul lui b
    if (nodes[a].in <= nodes[b].in && nodes[a].out >= nodes[b].out) {
        return a;
    }

    // cauta cel mai indepartat stramos al lui a
    // care NU este si stramos al lui b
    int pas2 = 16;
    while (pas2 >= 0) {
        if (dp[pas2][a] > 0) { // putem sa ne ducem in sus 2^pas2 nivele
            const auto& nod = nodes[dp[pas2][a]];
            if (!(nod.in <= nodes[b].in && nod.out >= nodes[b].out)) { // nu este stramos al lui b
                a = dp[pas2][a]; // urcam
            }
        }
        pas2--;
    }

    return nodes[a].parent;
}

int main() {
    std::ifstream fin("lca.in");
    std::ofstream fout("lca.out");
    int n, m;

    fin >> n >> m;
    for (int i = 2; i <= n; i++) {
        fin >> nodes[i].parent;
        nodes[nodes[i].parent].children.push_back(i);
        dp[0][i] = nodes[i].parent;
    }

    gen_dp(n);
    dfs(1);

    for (int i = 0; i < m; i++) {
        int a, b;
        fin >> a >> b;
        fout << lca(n, a, b) << '\n';
    }
    return 0;
}