Cod sursa(job #3155017)

Utilizator Luka77Anastase Luca George Luka77 Data 7 octombrie 2023 09:45:55
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>
using namespace std;

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

/// GLOBAL VARIABLES
const int NMAX = 1e5 + 5, LOG = 25;
int n, m, k;
int g[NMAX], depth[2*NMAX], euler[2*NMAX], poz[2*NMAX];
int rmq[LOG][2 * NMAX];
vector<int>graph[NMAX];

inline void DFS(int curr_node, int h)
{
    euler[++k] = curr_node;
    depth[k] = h;
    poz[curr_node] = k;

    for(auto new_node : graph[curr_node])
    {
        DFS(new_node, h + 1);
        euler[++k] = curr_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))];
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    fin.tie(NULL);
    fout.tie(NULL);

    fin >> n >> m;

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

    DFS(1, 0);
    RMQ();

    while(m--)
    {
        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 << euler[rmq[k][a]] << '\n';
        else
            fout << euler[rmq[k][b - (1 << k) + 1]] << '\n';
    }
}