Pagini recente » Cod sursa (job #1482709) | Cod sursa (job #1508632) | Cod sursa (job #2293288) | Cod sursa (job #1292613) | Cod sursa (job #2353129)
#include <bits/stdc++.h>
#define MAX 100100
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int n, m, t[MAX], lvl[MAX];
void facemlca (int a, int b){
while (t[a] != t[b]){
if (lvl[a] > lvl[b]){
a = t[a];
} else {
b = t[b];
}
}
while (a != b){
if (lvl[a] > lvl[b]){
a = t[a];
} else {
b = t[b];
}
}
g << a << '\n';
}
int main()
{
ios_base::sync_with_stdio(false);
f >> n >> m;
lvl[1] = 1;
for (int i = 1; i <= n-1; i++){
int x;
f >> x;
t[i+1] = x;
lvl[i+1] = lvl[x] + 1;
}
while (m--){
int a, b;
f >> a >> b;
facemlca (a,b);
}
return 0;
}