Pagini recente » Cod sursa (job #1326108) | Cod sursa (job #644971) | Cod sursa (job #310249) | Cod sursa (job #967753) | Cod sursa (job #3178848)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
vector <int> G[100005];
int n;
int t[100005][18];
int depth[100005];
void dfs(int r){
for(auto x : G[r]){
depth[x] = depth[r] + 1;
t[x][0] = r;
for(int i = 1; (1 << i) <= n; i++) t[x][i] = t[t[x][i - 1]][i - 1];
dfs(x);
}
}
int lca(int x, int y){
if(depth[x] < depth[y]) swap(x,y);
int d = depth[x] - depth[y];
for(int i = 17; i >= 0; i--){
if((1 << i) & d) x = t[x][i];
}
if(x == y) return x;
for(int i = 17; i >= 0; i--){
if(t[x][i] != t[y][i]){
x = t[x][i];
y = t[y][i];
}
}
return t[x][0];
}
int main()
{
int m,i,x,y;
fin >> n >> m;
t[1][0] = 1;
for(i = 2; i <= n; i++){
fin >> x;
G[x].push_back(i);
}
dfs(1);
for(i = 1; i <= m; i++){
fin >> x >> y;
fout << lca(x,y) << "\n";
}
return 0;
}