Pagini recente » Cod sursa (job #1402761) | Cod sursa (job #2390223) | Cod sursa (job #2627721) | Cod sursa (job #272673) | Cod sursa (job #2923335)
#include <fstream>
using namespace std;
ifstream cin ("lca.in");
ofstream cout ("lca.out");
int dp[100002][20], n, parent[1000002], LOG, m, x, y, depth[1000002];
void bl(){
for(int i = 1; i <= n; i++){
dp[i][0] = parent[i];
for(int j = 1; j < LOG; j++)
dp[i][j] = dp[ dp[i][j-1] ][j-1];
}
}
void lca(int x, int y){
if(depth[x] < depth[y]) swap(x,y);
int k = depth[x] - depth [y];
for(int j = LOG - 1; j >= 0; j--)
if(k & (1 << j))
x = dp[x][j];
if(x == y)
{cout << y << '\n'; return;}
for(int j = LOG - 1; j >= 0; j--)
if( dp[x][j] != dp[y][j]){
x = dp[x][j];
y = dp[y][j];
}
cout << dp[x][0] << '\n';
}
int main() {
cin >> n >> m;
for(int i = 2; i <= n; i++){
cin >> parent[i];
depth[i] = depth[parent[i]] + 1;}
parent[1] = 1;
while ((1 << LOG) <= n) LOG++;
bl();
for(int i = 1; i <= m; i++){
cin >> x >> y;
lca(x, y);
}
}