Cod sursa(job #2645343)

Utilizator dream3rDavid Pop dream3r Data 27 august 2020 20:30:46
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int lim = 1e5 + 4;
vector<int> vec[lim];
pair<int, int> tree[18][2 * lim];
int poz[lim], cnt;
int lg[2 * lim];
void df(int nod, int h)
{
	++cnt;
	poz[nod] = cnt;
	tree[0][cnt] = { h,nod };
	for (int x : vec[nod])
	{
		df(x, h + 1);
		++cnt;
		poz[nod] = cnt;
		tree[0][cnt] = { h,nod };
	}
}
void rmq()
{
	for (int i = 2; i <= cnt; ++i)
		lg[i] = lg[i / 2] + 1;
	for (int p = 1; p <= lg[cnt]; ++p)
		for (int i = 1; i + (1 << p) <= cnt + 1; ++i)
			tree[p][i] = min(tree[p - 1][i], tree[p - 1][i + (1 << (p - 1))]);
}
int ans(int x, int y)
{
	x = poz[x];
	y = poz[y];
	if (x > y) swap(x, y);
	int d = lg[y - x + 1];
	return min(tree[d][x], tree[d][y - (1 << d) + 1]).second;
}
int main()
{
	int n, q, x, y;
	in >> n >> q;
	for (int i = 2; i <= n; ++i)
		in >> x, vec[x].push_back(i);
	df(1, 1);
	rmq();
	while (q--)
	{
		in >> x >> y;
		out << ans(x, y) << '\n';
	}
	return 0;
}