Cod sursa(job #3228107)

Utilizator AndreasBossGamerBaragau Andreas AndreasBossGamer Data 5 mai 2024 19:35:03
Problema Lowest Common Ancestor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <algorithm>
#include <vector>	

using namespace std;

ifstream cin("lca.in");
ofstream cout("lca.out");

int n, q;
int rmq[18][100000];
vector<vector<int>> adj;
vector<int> depth;

void dfs(int node, int parent)
{
	for (auto vecin : adj[node])
	{
		if (vecin == parent)
			continue;

		rmq[0][vecin] = node;
		for (int e = 1; e <= 17; e++)
		{
			if (rmq[e - 1][vecin] == 0)
				break;

			rmq[e][vecin] = rmq[e - 1][rmq[e - 1][vecin]];
		}
		depth[vecin] = depth[node] + 1;
		dfs(vecin, node);
	}
}

int lca(int x, int y)
{
	if (depth[x] < depth[y]) swap(x, y);

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

	for (int e = 0; e <= 17; e++)
	{
		if (dif & (1 << e))
			x = rmq[e][x];
	}

	if (x == y) return x;

	for (int e = 17; e >= 0; e--)
	{
		if (rmq[e][x] != rmq[e][y])
		{
			x = rmq[e][x];
			y = rmq[e][y];
		}
	}

	

	if (x == y) return x;
	return rmq[0][x];
}

int main()
{
	cin >> n >> q;
	depth.resize(n + 1);
	adj.resize(n + 1);
	for (int i = 2; i <= n; i++)
	{
		int aux;
		cin >> aux;
		adj[aux].push_back(i);
		rmq[0][i] = aux;
	}

	dfs(1, 0);

	while (q--)
	{
		int x, y;
		cin >> x >> y;
		cout << lca(x, y) << '\n';
	}
}