Cod sursa(job #2574868)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 6 martie 2020 10:23:05
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <cmath>
using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

vector<int> g[100005];
int n, m;
vector<int> eul, l;
int rmq[20][200010];
int lg[200010];
int first[100005];

void citire() {
    fin >> n >> m;
    for(int i = 2; i <= n; i++) {
        int x;
        fin >> x;
        g[x].push_back(i);
    }
}

void dfs(int x, int lev) {
    eul.push_back(x);
    l.push_back(lev);
    first[x] = eul.size()-1;
    for(auto next: g[x]) {
        dfs(next, lev+1);
        eul.push_back(x);
        l.push_back(lev);
    }
}

void RMQ() {
    int k = eul.size();
    for(int i = 2; i <= k; i++)
        lg[i] = 1+lg[i/2];
    for(int i = 1; i <= k; i++)
        rmq[0][i] = i;
    for(int i = 1; (1<<i) <= k; i++)
        for(int j = 1; j +(1<<i) <= k; j++) {
            rmq[i][j] = rmq[i-1][j];
            if(l[rmq[i][j]] > l[rmq[i-1][j+(1<<(i-1))]])
                rmq[i][j] = rmq[i-1][j+(1<<(i-1))];
        }
}

int lca(int x, int y) {
    int a = first[x], b = first[y];
    if(a > b) swap(a, b);

    int dif = b-a+1;
    int logg = lg[dif];
    int res = rmq[logg][a];
    if(l[res] > l[rmq[logg][a+dif-(1<<logg)]])
        res = rmq[logg][a+dif-(1<<logg)];
    return eul[res];
}

int main() {
    citire();
    dfs(1, 0);
    RMQ();
    int a, b;
    while(m--) {
        fin >> a >> b;
        fout << lca(a, b) << '\n';
    }
}