Pagini recente » Cod sursa (job #2132761) | Cod sursa (job #2208490) | Cod sursa (job #786216) | Cod sursa (job #1244287) | Cod sursa (job #3266441)
#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];
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]) {
x = T[x];
}
while (x != y) {
x = T[x];
y = T[y];
}
return 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) swap(x, y);
fout << lca(x, y) << '\n';
}
return 0;
}