Pagini recente » Cod sursa (job #1038980) | Cod sursa (job #350707) | Cod sursa (job #36521) | Borderou de evaluare (job #2116785) | Cod sursa (job #3266438)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("lca.in");
ofstream fout ("lca.out");
const int NMAX = 1e5;
int N, M, T[NMAX + 2], x, y, nivel[NMAX + 2], ans;
vector<int> arbore[NMAX + 2];
void defese(int x, int niv) {
nivel[x] = niv;
for (int i : arbore[x]) {
defese(i, niv + 1);
}
}
int lca(int x, int y) {
while (nivel[x] != nivel[y]) {
if (T[x] == y) {
return y;
}
x = T[x];
}
while (T[x] != T[y]) {
x = T[x];
y = T[y];
}
return T[x];
}
int main() {
fin >> N >> M;
for (int i = 2; i <= N; i++) {
fin >> T[i];
arbore[T[i]].push_back(i);
}
if (nivel[x] < nivel[y]) swap(x, y);
defese(1, 1);
while (M--) {
fin >> x >> y;
if (x == y) fout << x << '\n';
else {
ans = 0;
if (x < y) swap(x, y);
fout << lca(x, y) << '\n';
}
}
return 0;
}