Cod sursa(job #2972312)

Utilizator sandupetrascoPetrasco Sandu sandupetrasco Data 29 ianuarie 2023 01:56:21
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>
#define PII pair < int , int >
#define NMAX 100100
#define LOG 17

using namespace std;

int n, m, D[NMAX][LOG], depth[NMAX];
vector <int> V[NMAX];
bitset<NMAX> B;

void dfs(int x) {
    for (auto it : V[x]) {
        D[it][0] = x;
        depth[it] = depth[x] + 1;

        for (int j = 1; j < LOG; j++) {
            D[it][j] = D[ D[it][j - 1] ][j - 1];
        }

        dfs(it);
    }
}

int lca(int x, int y) {
    if (depth[x] < depth[y]) {
        swap(x, y);
    }

    int k = depth[x] - depth[y];
    for (int j = LOG - 1; j >= 0; j--) {
        if (k & (1 << j)) {
            x = D[x][j];
        }
    }

    if (x == y) {
        return x;
    }

    for (int j = LOG - 1; j >= 0; j--) {
        if (D[x][j] != D[y][j]) {
            x = D[x][j];
            y = D[y][j];
        }
    }

    return D[x][0];
}

int main(){
    ifstream cin("lca.in");
    ofstream cout("lca.out");
    
    cin >> n >> m;
    for (int i = 2, x; i <= n; i++) {
        cin >> x;

        V[x].push_back(i);
    }

    depth[1] = 1;
    dfs(1);

    for (int i = 1; i <= n; i++) {
        cout << i << " ";
        for (int j = 0; j < log2(n); j++) {
            cout << j << " -> " << D[i][j] << '\n';
        }
    }

    while (m--) {
        int x, y;

        cin >> x >> y;

        cout << lca(x, y) << "\n";
    }

    return 0;
}