Cod sursa(job #3242091)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 8 septembrie 2024 17:41:10
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 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 dp[LOGMAX][NMAX];

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

void dfs(int nod)
{
    for(int i : v[nod])
    {
        depth[i] = depth[nod] + 1;

        dfs(i);
    }
}

void precalc()
{
    for(int i = 1; i < LOGMAX; i ++)
    {
        for(int j = 1; j <= n; j ++)
        {
            dp[i][j] = dp[i - 1][dp[i - 1][j]];
        }
    }
}

inline int f(int nod, int stramos)
{
    if(stramos == 0)
    {
        return nod;
    }

    for(int shift = LOGMAX - 1; shift >= 0; shift --)
    {
        if(stramos & (1 << shift))
        {
            nod = dp[shift][nod];

            stramos ^= (1 << shift);
        }
    }

    return nod;
}

inline int lca(int x, int y)
{
    if(depth[x] < depth[y])
    {
        std :: swap(x, y);
    }

    x = f(x, depth[x] - depth[y]);

    if(x == y)
    {
        return x;
    }

    for(int shift = LOGMAX - 1; shift >= 0; shift --)
    {
        if(dp[shift][x] == dp[shift][y])
        {
            continue;
        }
        else
        {
            x = dp[shift][x];

            y = dp[shift][y];
        }
    }

    return dp[0][x];
}

int main()
{

    in >> n >> q;

    for(int i = 2; i <= n; i ++)
    {
        in >> dp[0][i];

        v[dp[0][i]].push_back(i);
    }

    depth[1] = 1;

    dfs(1);

    precalc();

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

        out << lca(x, y) << '\n';
    }

    return 0;
}