Pagini recente » Cod sursa (job #3193020) | Cod sursa (job #1138118) | Cod sursa (job #2424741) | Cod sursa (job #1956436) | Cod sursa (job #2441621)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int n, l = 200;
int anc[MAXN];
int radanc[MAXN], niv[MAXN];
vector<int> graf[MAXN];
int dp[MAXN][30];
void batog(int nod, int tata, int nivel){
radanc[nod] = tata;
niv[nod] = nivel;
if(nivel % l == 0) tata = nod;
for(auto x:graf[nod])
batog(x, tata, nivel + 1);
}
void prec(){
batog(1, 0, 0);
for(int i = 1; i <= n; ++i) dp[i][0] = anc[i];
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= 20; ++j)
dp[i][j] = dp[dp[i][j - 1]][j - 1];
}
}
int solve1(int x, int y){
while(x != y){
if(x > y) x = anc[x];
else y = anc[y];
}
return x;
}
int solve2(int x, int y){
while(radanc[x] != radanc[y]){
if(niv[x] > niv[y]) x = radanc[x];
else y = radanc[y];
}
while(x != y){
if(niv[x] > niv[y]) x = anc[x];
else y = anc[y];
}
return x;
}
int solve3(int x, int y){
if(niv[x] < niv[y]) swap(x, y);
int log1 = 0, log2 = 0;
while(1 << log1 < niv[x]) log1++;
while(1 << log2 < niv[y]) log2++;
for(int p = log1; p >= 0; --p){
if(niv[x] - (1 << p) >= niv[y])
x = dp[x][p];
}
if(x == y) return x;
for(int p = log2; p >= 0; --p){
if(dp[x][p] && dp[x][p] != dp[y][p]){
x = dp[x][p];
y = dp[y][p];
}
}
return dp[x][0];
}
int main()
{
ifstream fin("lca.in");
ofstream fout("lca.out");
int m;
fin >> n >> m;
for(int i = 2; i <= n; ++i){
fin >> anc[i];
graf[anc[i]].push_back(i);
}
prec();
while(m){
int x, y;
fin >> x >> y;
fout << solve3(x, y) << "\n";
m--;
}
return 0;
}