Cod sursa(job #2976924)

Utilizator alexdumitrescuDumitrescu George Alex alexdumitrescu Data 10 februarie 2023 13:00:21
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>
#define Nmax 100005
#define LG 17

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

int tin[Nmax], tout[Nmax], t[Nmax][LG], n, m, o;
vector <int> v[Nmax];

void dfs(int x)
{
    tin[x] = ++o;

    for(auto it:v[x])
        if(it != t[x][0])
            dfs(it);

    tout[x] = ++o;
}

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

bool is_ancestor(int x, int y)
{
    if(tin[x] <= tin[y] && tout[y] <= tout[x])
        return 1;
    else return 0;
}

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

    if(is_ancestor(y, x))
        return y;

    for(int j=LG-1;j>=0;j--)
        if(!is_ancestor(t[x][j], y))
            x = t[x][j];

    return t[x][0];
}

int main()
{
    fin >> n >> m;

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

    dfs(1); ///radacina
    binary_lift();

    while(m--)
    {
        int x, y;
        fin >> x >> y;
        fout << lca(x, y) << '\n';
    }
    return 0;
}