Cod sursa(job #2739616)

Utilizator DragosC1Dragos DragosC1 Data 8 aprilie 2021 23:26:53
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int table[25][200001];
int lg[200001];
int new_ind[100001], cnt = 0;
int eul[200001], l = 0;
int first_encounter[100001];
int old_ind[200001];

vector<int> a[100001];

void dfs(int x, int px) {
    int i;
    new_ind[x] = ++cnt;
    old_ind[cnt] = x;
    eul[++l] = new_ind[x];
    first_encounter[x] = l;
    for (i = 0; i < a[x].size(); i++) {
        if (a[x][i] == px) continue;
        dfs(a[x][i], x);
        eul[++l] = new_ind[x];
    }
}   

int main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int n, m, i, j, x, aux, y, r, Min;
    cin >> n >> m;
    for (i = 2; i <= n; i++) {
        cin >> x;
        a[x].emplace_back(i);
        a[i].emplace_back(x);
    }

    dfs(1, 0);

    //preprocess
    for (i = 2; i <= l; i++)
        lg[i] = lg[i / 2] + 1;

    for (i = 1; i <= l; i++)
        table[0][i] = eul[i];
    for (i = 1; i <= 24; i++)
        for (j = 1; j + (1 << i) - 1 <= l; j++) {
            aux = (1 << (i - 1));
            table[i][j] = min(table[i - 1][j], table[i - 1][j + aux]);
        }
    for (i = 1; i <= m; i++) {
        cin >> x >> y;
        x = first_encounter[x];
        y = first_encounter[y];
        if (x > y)
            swap(x, y);
        r = lg[y - x + 1];
        cout << old_ind[min(table[r][x], table[r][y - (1 << r) + 1])] << '\n';
    }   
    return 0;
}