Pagini recente » Cod sursa (job #2346046) | Cod sursa (job #2913652) | Cod sursa (job #1998388) | Cod sursa (job #1392151) | Cod sursa (job #2649301)
#include <bits/stdc++.h>
using namespace std;
struct Node { int parent = -1, jump = -1, depth; };
vector<Node> T;
void Init(int node) {
if (T[node].jump != -1) return;
int par = T[node].parent;
if (par == -1) {
T[node].depth = 0;
T[node].jump = node;
} else {
Init(par);
T[node].depth = 1 + T[par].depth;
int mid = T[par].jump;
if (T[node].depth + T[T[mid].jump].depth == 2 * T[mid].depth)
T[node].jump = T[mid].jump;
else T[node].jump = par;
}
}
int Query(int a, int b) {
Init(a); Init(b);
if (T[a].depth < T[b].depth) swap(a, b);
while (T[a].depth > T[b].depth)
a = (T[T[a].jump].depth >= T[b].depth ? T[a].jump : T[a].parent);
while (a != b) {
if (T[a].jump != T[b].jump)
a = T[a].jump, b = T[b].jump;
else a = T[a].parent, b = T[b].parent;
}
return a;
}
int main() {
ifstream cin("lca.in");
ofstream cout("lca.out");
int n, q; cin >> n >> q;
T.resize(n);
for (int i = 1; i < n; ++i) {
int par; cin >> par; --par;
T[i].parent = par;
}
for (int i = 0; i < q; ++i) {
int a, b; cin >> a >> b; --a; --b;
cout << Query(a, b) + 1 << '\n';
}
}