Pagini recente » Cod sursa (job #789481) | Cod sursa (job #1603596) | Cod sursa (job #706473) | Cod sursa (job #2091038) | Cod sursa (job #3137094)
#include <fstream>
#include <vector>
#include <algorithm>
#define int long long
using namespace std;
const int MAX = 1e5 + 1;
ifstream cin("lca.in");
ofstream cout("lca.out");
vector <int> g[MAX];
int n , x , q , y , bbl[19][MAX] , tin[MAX] , tout[MAX] , tm;
void dfs( int x , int t ){
bbl[0][x] = t;
for(int i = 1 ; i <= 18 ; i++){
bbl[i][x] = bbl[i-1][bbl[i-1][x]];
}
tin[x] = ++tm;
for(auto it : g[x]){
dfs(it,x);
}
tout[x] = ++tm;
}
bool ispapa( int &x , int &t ){
return(tin[t]<=tin[x]&&tout[x]<=tout[t]);
}
signed main()
{
cin >> n >> q;
for(int i = 2 ; i <= n ; i++){
cin >> x;
g[x].push_back(i);
}
dfs(1,0);
while(q--){
cin >> x >> y;
if(!ispapa(y,x)){
int step = 18;
while(step >= 0){
if(bbl[step][x] && !ispapa(y,bbl[step][x])){
x = bbl[step][x];
}
step--;
}
}
if(!ispapa(y,x)) x = bbl[0][x];
cout << x << '\n';
}
return 0;
}