Cod sursa(job #3171894)

Utilizator alexgroparuObada Alex alexgroparu Data 19 noiembrie 2023 18:48:33
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;

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

using VI  = vector<int>;
using VVI = vector<VI>;

int LCA(int x, int y);
int Stramos(int nod, int p);

VI niv;
VVI stramos;

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

    niv = VI(n + 1);
    stramos = VVI(log2(n) + 1, VI(n + 1));

    for(int i = 2, x; i <= n; ++i)
    {
        fin >> x; 
        stramos[0][i] = x;
        niv[i] = niv[x] + 1;
    }

    for(int i = 1; (1 << i) <= n; ++i)
        for(int j = 1; j <= n; ++j)
            stramos[i][j] = stramos[i - 1][stramos[i - 1][j]];
    
    for (int i = 1, x, y; i <= m; ++i)
    {
        fin >> x >> y;
		fout << LCA(x, y) << '\n';
    }

    return 0;
}

int LCA(int x, int y)
{
    if(niv[x] < niv[y])
        swap(x, y);

    int dif = niv[x] - niv[y];
    x = Stramos(x, dif);

    if(x == y) 
        return x;

    for(int i = log2(niv[x]); i >= 0; --i)
        if(stramos[i][x] != stramos[i][y])
        {
            x = stramos[i][x];
            y = stramos[i][y];
        }

    return stramos[0][x];
}

int Stramos(int nod, int p)
{
    int i = 0;
    while (p)
    {
        if (p & 1)
            nod = stramos[i][nod];

        i++;
        p >>= 1;
    }
    return nod;
    
}