Cod sursa(job #2908415)

Utilizator AndreiN96Andrei Nicula AndreiN96 Data 3 iunie 2022 11:50:19
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>

using namespace std;

const int N = 1e5, L = 17;
int t[L][N + 1];
vector <int> fii[N + 1];
int ti[L], to[L];
int n, m, timp;

void calcul_t()
{
    for (int e = 1; e <= L; e ++)
    {
        for (int i = 1; i <= n; i ++)
        {
            t[e][i] = t[e - 1][t[e - 1][i]];
        }
    }
}
void dfs(int x)
{
    ti[x] = ++timp;
    for (auto y: fii[x])
    {
        dfs(y);
    }
    to[x] = ++timp;
}
bool stramos(int x, int y)
{
    return (ti[x] <= ti[y] && to[y] <= to[x]);
}
int lca(int x, int y)
{
    if (stramos(x, y))
        return x;
    for (int e = L; e >= 0; e --)
    {
        if (t[e][x] != 0 && !stramos(t[e][x], y));
        {
            x = t[e][x];
        }
    }
    return t[0][x];
}
int main()
{
    ifstream in("lca.in");
    ofstream out("lca.out");

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

    calcul_t();
    dfs(1);

/*
    for (int i = 1; i <= L; i ++)
    {
        out << ti[i] << ' ';
    }
    out << '\n';
    for (int j = 1; j <= L; j ++)
    {
        out << to[j] << ' ';
    }
*/

    for (int i = 0; i < m; i ++)
    {
        int x, y;
        in >> x >> y;
        out << lca(x, y) << '\n';
    }

    in.close();
    out.close();

    return 0;
}