Cod sursa(job #2550562)

Utilizator Alin_StanciuStanciu Alin Alin_Stanciu Data 18 februarie 2020 21:10:50
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

int n, m, T[100001], I[100001];
vector<int> G[100001], E, N;
vector<pair<int, int>> M[21];

void Dfs(int x, int niv)
{
    E.push_back(x);
    N.push_back(niv);
    I[x] = E.size() - 1;
    for (int y : G[x])
    {
        Dfs(y, niv + 1);
        E.push_back(x);
        N.push_back(niv);
    }
}

void Prep()
{
    for (int i = 0; i < N.size(); ++i)
        M[0].emplace_back(N[i], E[i]);
    for (int e = 1, p = 2; p <= N.size(); ++e, p *= 2)
    {
        for (int i = 0; i <= N.size() - p; ++i)
        {
            if (M[e - 1][i].first < M[e - 1][i + p / 2].first)
                M[e].push_back(M[e - 1][i]);
            else M[e].push_back(M[e - 1][i + p / 2]);
        }
    }
}

int Lca(int x, int y)
{
    int a = I[x], b = I[y];
    if (a > b)
        swap(a, b);
    int e = 0, p = 1;
    while (p * 2 <= b - a + 1)
    {
        p *= 2;
        ++e;
    }
    if (M[e][a].first < M[e][b - p + 1].first)
        return M[e][a].second;
    else return M[e][b - p + 1].second;
}

int main()
{
    fin >> n >> m;
    for (int i = 2; i <= n; ++i)
    {
        fin >> T[i];
        G[T[i]].push_back(i);
    }
    Dfs(1, 1);
    Prep();
    for (int i = 1; i <= m; ++i)
    {
        int x, y;
        fin >> x >> y;
        fout << Lca(x, y) << '\n';
    }

    return 0;
}