Pagini recente » Cod sursa (job #1619080) | Cod sursa (job #2838056) | Cod sursa (job #648918) | Cod sursa (job #1621241) | Cod sursa (job #3005643)
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int MAX_N = 100000;
int n, m;
int depth[MAX_N];
int ancestors[20][MAX_N];
vector <int> graph[MAX_N];
void DFS(int node, int d) {
depth[node] = d;
for (int i = 1; i < 20; i++) {
ancestors[i][node] = ancestors[i - 1][ancestors[i - 1][node]];
}
for (int newNode : graph[node]) {
DFS(newNode, d + 1);
}
}
int main() {
fin >> n >> m;
for (int i = 2; i <= n; i++) {
int node;
fin >> node;
ancestors[0][i] = node;
graph[node].push_back(i);
}
DFS(1, 1);
for (int i = 1; i <= m; i++) {
int a, b;
fin >> a >> b;
if (depth[a] < depth[b]) {
swap(a, b);
}
int depthDiff = depth[a] - depth[b];
for (int i = 0; i < 20; i++) {
if (depthDiff & (1 << i)) {
a = ancestors[i][a];
}
}
if (a == b) {
fout << a << '\n';
continue;
}
for (int e = 19; e >= 0; e++) {
if (ancestors[e][a] != ancestors[e][b]) {
a = ancestors[e][a];
b = ancestors[e][b];
}
}
fout << ancestors[0][a] << '\n';
}
}