Cod sursa(job #2960927)

Utilizator domistnSatnoianu Dominic Ioan domistn Data 5 ianuarie 2023 12:51:56
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1e5,
          LGMAX = 20;

int n, m, a[NMAX + 1], etl, first[NMAX + 1], niv[NMAX + 1],
    lg2[2 * NMAX + 1], sparse[2 * NMAX + 1][LGMAX + 1];
vector<int> adj[NMAX + 1], eulerTour;

void precalcLg2() {
    lg2[1] = 0;
    for(int i = 2; i <= 2 * NMAX; ++i)
        lg2[i] = lg2[i / 2] + 1;
}

void dfs(int nod = 1, int par = -1, int nivCrt = 0) {
    niv[nod] = nivCrt;
    first[nod] = eulerTour.size();
    eulerTour.push_back(nod);
    for(const auto &el : adj[nod]) {
        if(el == par) continue;
        dfs(el, nod, nivCrt + 1);
        eulerTour.push_back(nod);
    }
}

void constructSparse() {
    for(int i = 1; i <= etl; ++i)
        sparse[i][0] = eulerTour[i];
    for(int sz = 1; (1 << sz) <= etl; ++sz)
        for(int i = 1; i + (1 << sz) - 1 <= etl; ++i) {
            const int v1 = sparse[i][sz - 1],
                      v2 = sparse[i + (1 << (sz - 1))][sz - 1];
            if(niv[v1] < niv[v2]) sparse[i][sz] = v1;
            else sparse[i][sz] = v2;
        }
}

int lca(int x, int y) {
    x = first[x], y = first[y];
    if(x > y) swap(x, y);
    const int lg2dist = lg2[y - x + 1],
              v1 = sparse[x][lg2dist],
              v2 = sparse[y - (1 << lg2dist) + 1][lg2dist];
    if(niv[v1] < niv[v2]) return v1;
    return v2;
}

int main()
{
    precalcLg2();

    fin >> n >> m;
    for(int i = 2, x; i <= n; ++i)
        fin >> x,
        adj[x].push_back(i),
        adj[i].push_back(x);

    eulerTour.push_back(0);
    dfs();
    etl = eulerTour.size() - 1;

    constructSparse();

    for(int i = 1, x, y; i <= m; ++i) {
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }
    return 0;
}