Cod sursa(job #3164563)

Utilizator angelaAngela Visuian angela Data 3 noiembrie 2023 17:59:28
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
// 361 ms
#include <fstream>
#include <cmath>
using namespace std;

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

#define NMAX 100005

int str[20][NMAX];
int niv[NMAX];

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


int main()
{
    int n, m;
    fin >> n >> m;
	int tata;
	for (int i = 2; i <= n; ++i)
	{
		fin >> tata;
		str[0][i] = tata;
		niv[i] = niv[tata] + 1;
	}
	
	for (int i = 1; (1 << i) <= n; ++i)
		for (int j = 1; j <= n; ++j)
			if (str[i - 1][j])
				str[i][j] = str[i - 1][str[i - 1][j]];
   
	int x, y;
    for (int i = 1; i <= m; ++i)
    {       
        fin >> x >> y;

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

        int dif = niv[x] - niv[y];

        x = Stramos(x, dif);

		if (x == y)
			fout << x << '\n';
		else
			fout << LCA(x, y) << '\n';
    }
    return 0;
}

int LCA(int x, int y)
{
    int e = log2(niv[x]);
    while (e >= 0)
    {
        if (str[e][x] != str[e][y])
        {
            x = str[e][x];
            y = str[e][y];
        }
        e--;
    }
    return str[0][x];
}

int Stramos(int nod, int dist)
{
    int i = 0;
    while (dist)
    {
        if (dist & 1)
            nod = str[i][nod];
        i++;
        dist >>= 1;
    }
    return nod;
}