Cod sursa(job #3004018)

Utilizator Luka77Anastase Luca George Luka77 Data 16 martie 2023 08:46:41
Problema Lowest Common Ancestor Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define FOR(WHATEVER) for(int i = 1; i <= WHATEVER; ++ i)

/// INPUT / OUTPUT
const string problem = "lca";
ifstream fin(problem + ".in");
ofstream fout(problem + ".out");

/// GLOBAL VARIABLES
const ll NMAX = 1e5+5, MOD = 1e9 + 7, INF = 1e9;
int n, q, k;
bool viz[NMAX];
int lin[NMAX], depth[NMAX], poz[NMAX];
vector<int>g[NMAX];
int rmq[25][NMAX];

inline void dfs(int node, int h)
{
    lin[++k] = node;
    depth[k] = h;
    poz[node] = k;
    for(auto new_node : g[node])
    {
        viz[new_node] = 1;
        dfs(new_node, h + 1);
        lin[++k] = node;
        depth[k] = h;
    }
}

inline void RMQ()
{
    for(int i = 1; i <= k; ++ i)
        rmq[0][i] = i;
    for(int i = 1; (1 << i) <= k; ++ i)
    {
        for(int j = 1; j <= k; ++ j)
        {
            if(depth[rmq[i-1][j]] < depth[rmq[i-1][j + (1 << (i-1))]])
                rmq[i][j] = rmq[i-1][j];
            else
                rmq[i][j] =rmq[i-1][j + (1 << (i - 1))];
        }
    }
}

/// READING THE INPUT
int main()
{
    ios::sync_with_stdio(false);
    fin.tie(NULL);
    fout.tie(NULL);

    fin >> n >> q;

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

    dfs(1, 0);
    RMQ();

    while(q--)
    {
        int a, b;
        fin >> a >> b;
        a = poz[a];
        b = poz[b];
        if(a > b)
            swap(a, b);
        int k = log2(b - a + 1);
        if(depth[rmq[k][a]] < depth[rmq[k][b - (1<<k) + 1]])
            fout << lin[rmq[k][a]] << '\n';
        else
            fout << lin[rmq[k][b - (1 << k) + 1]] << '\n';
    }

}