Pagini recente » Cod sursa (job #3135495) | Cod sursa (job #3248586) | Cod sursa (job #1435911) | Cod sursa (job #1338307) | Cod sursa (job #2862737)
#include <iostream>
#include <fstream>
std::ifstream in("lca.in");
std::ofstream out("lca.out");
const int N=100000;
const int LOG=16;
int dp[N+1][LOG+1];
int depth[N+1];
int n, m;
void preprocess()
{
for(int l=1; l<=LOG; l++)
{
for(int i=1; i<=n; i++)
{
dp[i][l]=dp[dp[i][l-1]][l-1];
}
}
}
int query(int x, int y)
{
/// x este mai jos ca y
if(depth[x]<=depth[y])
{
std::swap(x, y);
}
/// aducem la acelasi nivel
int diff=depth[x]-depth[y];
for(int i=LOG; i>=0; i--)
{
if(diff>=(1<<i))
{
x=dp[x][i];
diff-=1<<i;
}
}
///calculam
if(x==y) return x;
for(int i=LOG; i>=0; i--)
{
if(dp[x][i]!=dp[y][i])
{
x=dp[x][i];
y=dp[y][i];
}
}
return dp[x][0];
}
int main()
{
depth[1]=1;
in>>n>>m;
for(int i=2; i<=n; i++)
{
in>>dp[i][0];
depth[i]=1+depth[dp[i][0]];
}
preprocess();
int x, y;
for(int i=1; i<=m; i++)
{
in>>x>>y;
out<<query(x, y)<<"\n";
}
}