Pagini recente » Cod sursa (job #2683918) | Cod sursa (job #2339716) | Cod sursa (job #938353) | Cod sursa (job #1967854) | Cod sursa (job #3178830)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n;
int t[100005][18];
int depth[100005];
void gent(){
for(int j = 1; (1 << j) <= n; j++){
for(int i = 1; i <= n; i++) t[i][j] = t[t[i][j - 1]][j - 1];
}
}
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 >> t[i][0];
depth[i] = depth[t[i][0]] + 1;
}
for(i = 1; i <= m; i++){
fin >> x >> y;
fout << lca(x,y) << "\n";
}
return 0;
}