Cod sursa(job #1537001)

Utilizator deividFlorentin Dumitru deivid Data 26 noiembrie 2015 20:34:22
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <stdio.h>
#include <vector>

#define maxdim 100005

using namespace std;

int n;
int lanturi;
int lant[maxdim], nivel[maxdim], height[maxdim], chainParent[maxdim];
vector<int> G[maxdim];

void dfs(int nod) {
	
	height[nod] = 1;
	int optimal = 0;
	for (int son : G[nod]) {
		nivel[son] = nivel[nod] + 1;
		dfs(son);
		height[nod] += height[son];
		chainParent[lant[son]] = nod;
		if (height[son] > height[optimal]) {
			optimal = son;
		}
	}
	
	if (!optimal) {
		lant[nod] = ++lanturi;
	} else {
		lant[nod] = lant[optimal];
	}
}

inline int lca(int x, int y) {
	
	while (lant[x] != lant[y]) {
		if (nivel[chainParent[lant[x]]] >= nivel[chainParent[lant[y]]]) {
			x = chainParent[lant[x]];
		} else {
			y = chainParent[lant[y]];
		}
	}
	
	return nivel[x] <= nivel[y] ? x : y;
}

int main() {

	freopen("lca.in", "r", stdin);
	freopen("lca.out", "w", stdout);
	
	int q;
	scanf("%d %d", &n ,&q);
	for (int i = 2; i <= n; ++i) {
		int t; scanf("%d", &t);
		G[t].push_back(i);
	}
	
	nivel[1] = 1;
	dfs(1);
	chainParent[lant[1]] = 0;
	
	while (q--) {
		int x, y; scanf("%d %d", &x, &y);
		printf("%d\n", lca(x, y));
	}

	return 0;
}