Cod sursa(job #2646893)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 2 septembrie 2020 13:08:43
Problema Lowest Common Ancestor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

using namespace std;

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

void usain_bolt()
{
    ios::sync_with_stdio(false);
    fin.tie(0);
}

const int N = 1e5 + 5;

vector < int > a[N];

int tour[N * 4], height[N], rmq[25][N], lg[N * 4], first[N];
bool f[N];

void dfs(int k)
{
    tour[++tour[0]] = k;
    first[k] = tour[0];
    f[k] = true;
    for(auto v : a[k]) {
        if(f[v] == false) {
            height[v] = height[k] + 1;
            dfs(v);
            tour[++tour[0]] = k;
        }
    }
}

int main()
{
    usain_bolt();

    int n, q;

    fin >> n >> q;
    for(int i = 1; i < n; ++i) {
        int x;

        fin >> x;
        a[x].push_back(i + 1);
        a[i + 1].push_back(x);
    }
    height[1] = 1;
    dfs(1);
    for(int i = 2; i <= tour[0]; ++i) lg[i] = lg[i >> 1] + 1;
    for(int i = 1; i <= tour[0]; ++i) rmq[0][i] = tour[i];
    for(int i = 1; (1 << i) <= tour[0]; ++i) {
        for(int j = 1; j + (1 << i) - 1 <= tour[0]; ++j) {
            rmq[i][j] = height[rmq[i - 1][j]] >= height[rmq[i - 1][j + (1 << (i - 1))]] ? rmq[i - 1][j + (1 << (i - 1))] : rmq[i - 1][j];
        }
    }
    for(; q; --q) {
        int x, y;

        fin >> x >> y;
        x = first[x];
        y = first[y];
        if(x > y) swap(x, y);
        int dif = y - x + 1;
        int base = lg[dif];
        fout << ((height[rmq[base][x]] > height[rmq[base][y - (1 << base) + 1]]) ? rmq[base][y - (1 << base) + 1] : rmq[base][x]) << "\n";
    }
    return 0;
}