Cod sursa(job #3308899)

Utilizator Iustin_Mircea2010Iustin Mircea Iustin_Mircea2010 Data 29 august 2025 16:32:26
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>

using namespace std;

int h[100005], arb[100005], head[100005], parent[100005], heavyson[100005];
vector<int> child[100005];

void dfs(int u) {
    arb[u] = 1;
    for (int v : child[u]) {
        dfs(v);
        arb[u] += arb[v];
        if (arb[v] > arb[heavyson[u]]) {
            heavyson[u] = v;
        }
    }
}

void decomp(int u, bool newchain = 1) {
    if (newchain) {
        head[u] = u;
    }
    else
        head[u] = head[parent[u]];
    for (int v : child[u]) {
        if (v == heavyson[u]) {
            decomp(v, 0);
        }
        else
            decomp(v, 1);
    }
}

int solve(int u, int v) {
    while (head[u] != head[v]) {
        if (h[head[u]] < h[head[v]])
            swap(u, v);
        u = parent[head[u]];
    }
    return h[u] < h[v] ? u : v;
}

int main() {

    ifstream cin("lca.in");
    ofstream cout("lca.out");

    int n, q;
    cin >> n >> q;
    h[1] = 1;
    for (int i = 2; i <= n; i++) {
        int a;
        cin >> a;
        parent[i] = a;
        child[a].push_back(i);
        h[i] = h[a] + 1;
    }
    dfs(1);
    decomp(1);
    while (q--) {
        int u, v;
        cin >> u >> v;
        cout << solve(u, v) << '\n';
    }
    return 0;
}