Cod sursa(job #3134587)

Utilizator Razvan_GabrielRazvan Gabriel Razvan_Gabriel Data 29 mai 2023 18:14:38
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>

using namespace std;

const int N = 1e5;
const int L = 16;
const int INF = 1e9;


int n, t[L+1][N+1], b[L+1][N+1], t_i[N+1], t_o[N+1], timp;
vector <int> a[N+1];

void dfs(int x)
{
    t_i[x] = ++timp;
    for (auto y: a[x])
        if (t_i[y] == 0)
        {
            t[0][y] = x;
            dfs(y);
        }

    t_o[x] = ++timp;
}

void constructie_t()
{
    for (int i = 1; (1 << i) <= n; i++)
        for (int j = 1; j <= n; j++)
            t[i][j] = t[i-1][t[i-1][j]];

}

bool este_stramos(int x, int y)
{
    return (t_i[x] <= t_i[y] && t_o[y] <= t_o[x]);
}

int lca(int x, int y)
{
    if (este_stramos(x, y))
        return x;

    int pas = L;
    while (pas >= 0)
    {
        if (t[pas][x] != 0 && !este_stramos(t[pas][x] , y))
            x = t[pas][x];

        pas--;
    }
    return t[0][x];
}

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

    int m;

    fin >> n >> m;
    for (int i = 2; i <= n; i++)
    {
        fin >> t[0][i];
        a[t[0][i]].push_back(i);
    }

    dfs(1);
    constructie_t();

    for (int i = 0; i < m; i++)
    {
        int x, y;
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }

    return 0;
}