Cod sursa(job #3280559)

Utilizator vladm98Munteanu Vlad vladm98 Data 26 februarie 2025 17:38:51
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>

using namespace std;

int dp[21][100005];
int height[100005];
vector <int> graph[100005];

void buildHeights(int node, int h) {
    height[node] = h;

    for (auto x : graph[node]) {
        buildHeights(x, h + 1);
    }
}

int getLca(int x, int y) {
    if (height[x] < height[y]) {
        swap(x, y);
    }
    // stiu sigut ca x are inaltime mai mare
    int k = height[x] - height[y];

    for (int i = 0; i <= 20; ++i) {
        if ((1 << i) & k) {
            x = dp[i][x];
        }
    }

    // acum au inaltimi egale
    if (x == y) return x;

    for (int i = 20; i >= 0; i--) {
        if (dp[i][x] != dp[i][y]) {
            x = dp[i][x];
            y = dp[i][y];
        }
    }

    return dp[0][x];
}


int main()
{
    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n, m;
    cin >> n >> m;
    for (int i = 2; i <= n; i++) {
        cin >> dp[0][i];
        graph[dp[0][i]].push_back(i);
    }
    buildHeights(1, 1);
    for (int i = 1; i <= 20; ++i) {
        for (int j = 1; j <= n; ++j) {
            dp[i][j] = dp[i - 1][dp[i - 1][j]];
        }
    }
    for (int i = 1; i <= m; ++i) {
        int x, y;
        cin >> x >> y;
        cout << getLca(x, y) << '\n';
    }
    return 0;
}