Pagini recente » Cod sursa (job #618429) | Cod sursa (job #227205) | Cod sursa (job #2914047) | Cod sursa (job #2209182) | Cod sursa (job #2196030)
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m, dp[18][N], lvl[N];
vector <int> v[N];
void dfs(int q, int t){
lvl[q] = t;
for (auto it: v[q])
if (!lvl[it]) dfs(it, t + 1);
}
int main(){
ifstream cin ("lca.in");
ofstream cout ("lca.out");
cin >> n >> m;
for (int i=2; i<=n; i++) cin >> dp[0][i], v[dp[0][i]].push_back(i);
dfs(1, 1);
for (int i=1; (1<<i)<=n; i++){
for (int j = 1; j<=n; j++)
dp[i][j] = dp[i-1][dp[i-1][j]];
}
while (m--){
int x, y;
cin >> x >> y;
if (lvl[y] > lvl[x]) swap(x, y);
while (lvl[x] > lvl[y]){
int put = 0;
while (lvl[dp[put+1][x]] > lvl[y]) put++;
x = dp[put][x];
}
while (x != y){
int put = 0;
while (dp[put+1][x] != dp[put+1][y]) put++;
x = dp[put][x]; y = dp[put][y];
}
cout << x << "\n";
}
return 0;
}