Cod sursa(job #3242250)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 10 septembrie 2024 15:07:23
Problema Lowest Common Ancestor Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <bits/stdc++.h>

const std :: string FILENAME = "lca";

std :: ifstream in (FILENAME + ".in");

std :: ofstream out (FILENAME + ".out");

const int NMAX = 1e5 + 5;

const int LOGMAX = 17;

int n;

int q;

int x;

int y;

int depth[NMAX];

int first[NMAX];

int dp[LOGMAX][NMAX];

std :: vector <int> v[NMAX];

std :: vector <int> tour;

std :: bitset <NMAX> visited;

void euler(int nod)
{
    tour.push_back(nod);

    first[nod] = tour.size() - 1;

    for(int i : v[nod])
    {
        if(visited[i] == false)
        {
            depth[i] = depth[nod] + 1;

            visited[i] = true;

            euler(i);

            tour.push_back(nod);
        }
    }
}

void precalc()
{
    for(int i = 0; i < tour.size(); i ++)
    {
        dp[0][i] = tour[i];
    }

    for(int i = 1; i < LOGMAX; i ++)
    {
        for(int j = 0; j + (1 << i) <= tour.size(); j ++)
        {
            if(depth[dp[i - 1][j]] < depth[dp[i - 1][j + (1 << (i - 1))]])
            {
                dp[i][j] = dp[i - 1][j];
            }
            else
            {
                dp[i][j] = dp[i - 1][j + (1 << (i - 1))];
            }
        }
    }
}

int main()
{

    in >> n >> q;

    for(int i = 2; i <= n; i ++)
    {
        in >> x;

        v[x].push_back(i);
    }

    euler(1);

    precalc();

    while(q --)
    {
        in >> x >> y;

        x = first[x];

        y = first[y];

        if(x > y)
        {
            std :: swap(x, y);
        }

        int lg = log2(y - x + 1);

        if(depth[dp[lg][x]] < depth[dp[lg][y - (1 << lg) + 1]])
        {
            out << dp[lg][x] << '\n';
        }
        else
        {
            out << dp[lg][y - (1 << lg) + 1] << '\n';
        }
    }

    return 0;
}