Cod sursa(job #2544668)

Utilizator radustn92Radu Stancu radustn92 Data 12 februarie 2020 12:42:58
Problema Lowest Common Ancestor Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int NMAX = 100505;
const int LMAX = (1 << 18);
int N, M;
vector<int> G[NMAX];
int euler[LMAX], firstEuler[NMAX], depth[NMAX], eulerIdx;
bool visited[NMAX];

void read() {
	scanf("%d%d", &N, &M);
	int x;
	for (int node = 2; node <= N; node++) {
		scanf("%d", &x);
		G[x].push_back(node);
		G[node].push_back(x);
	}
}

void dfs(int node) {
	visited[node] = true;
	euler[++eulerIdx] = node;
	firstEuler[node] = eulerIdx;
	for (auto neighbour : G[node]) {
		if (!visited[neighbour]) {
			depth[neighbour] = depth[node] + 1;
			dfs(neighbour);
			euler[++eulerIdx] = node;
		}
	}
}

inline int lowerDepth(int node1, int node2) {
	return depth[node1] < depth[node2] ? node1 : node2;
}

int findNodeLowestDepth(int from, int to) {
	if (from > to) {
		swap(from, to);
	}

	int nodeLowestDepth = euler[from];
	for (int posEuler = from + 1; posEuler <= to; posEuler++) {
		nodeLowestDepth = lowerDepth(nodeLowestDepth, euler[posEuler]);
	}
	return nodeLowestDepth;
}

void solve() {
	dfs(1);
	int x, y;
	for (int queryIdx = 0; queryIdx < M; queryIdx++) {
		scanf("%d%d", &x, &y);
		printf("%d\n", findNodeLowestDepth(firstEuler[x], firstEuler[y]));
	}
}

int main() {
	freopen("lca.in", "r", stdin);
	freopen("lca.out", "w", stdout);

	read();
	solve();
	return 0;
}