Cod sursa(job #2979092)

Utilizator Iordache_CezarIordache Cezar Iordache_Cezar Data 14 februarie 2023 19:30:46
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
#define NMAX 100008

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

int n, m, t[NMAX][30], timp, prag;
int tin[NMAX], tout[NMAX];
vector <int> G[NMAX];

void DFS(int nod);
bool is_ancestor(int x, int y);

int main()
{
    int x, y;
    fin >> n >> m;
    for (int i = 2; i <= n; i++)
    {
        fin >> x;
        G[x].push_back(i);
    }
    prag = (int)(log2(n));
    DFS(1);
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        if (is_ancestor(x, y))
            fout << x << '\n';
        else if (is_ancestor(y, x))
            fout << y << '\n';
        else
        {
            for (int j = prag; j >= 0; j--)
            {
                if (is_ancestor(t[y][j], x) == 0)
                    y = t[y][j];
            }
            fout << t[y][0] << '\n';
        }
    }
    return 0;
}

void DFS(int nod)
{
    tin[nod] = ++timp;
    for (auto vf : G[nod])
    {
        t[vf][0] = nod;
        for (int j = 1; j <= prag; j++)
            t[vf][j] = t[t[vf][j-1]][j-1];
        DFS(vf);
    }
    tout[nod] = ++timp;
}

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