Cod sursa(job #2604869)

Utilizator tomitza.1604Sacuiu TomaAndrei tomitza.1604 Data 23 aprilie 2020 17:58:34
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int L = 18;
int n, m, nr, timp, vf[100001], urm[100001], lst[100001], t[L][100001], tb[100001], to[100001];

void add(int x, int y) {
	vf[++nr] = y;
	urm[nr] = lst[x];
	lst[x] = nr;
}

void dfs(int x) {
	tb[x] = ++timp;
	int y;
	for (int p = lst[x]; p != 0; p = urm[p]) {
		y = vf[p];
		if (tb[y] == 0) {
			dfs(y);
			t[0][y] = x;
		}
	}
	to[x] = ++timp;
}

int lca(int x, int y) {
	if (tb[x] <= tb[y] && to[y] <= to[x])
	{
		return x;
	}
	int pas = L - 1;
	int s;
	while (pas >= 0) {
		s = t[pas][x];
		if (s != 0 && ((tb[s] > tb[y]) || (to[s] < to[y]))) {
			x = s;
        }
		pas--;
	}
	return t[0][x];
}

int main() {
	in >> n >> m;
	for (int i = 2; i <= n; i++) {
		int a;
		in >> a;
		add(a, i);
	}
	dfs(1);
	for (int i = 1; (1 << i) <= n; i++){
		for (int j = 1; j <= n; j++){
			t[i][j] = t[i - 1][t[i - 1][j]];
        }
	}
	for (int i = 1; i <= m; i++) {
		int x, y;
		in >> x >> y;
		out << lca(x, y) << '\n';
	}
	return 0;

}