Pagini recente » Cod sursa (job #1734851) | Cod sursa (job #1938631) | Cod sursa (job #1269138) | Cod sursa (job #2921708) | Cod sursa (job #2418971)
#include <fstream>
#include <math.h>
using namespace std;
#define maxn 100005
int father[maxn],p[maxn],level[maxn],n,m,nod,r,son[1][maxn];
ifstream cin("lca.in");
ofstream cout("lca.out");
void LCA(int x, int y){
while(p[x]!=p[y]){
if(level[x]>level[y])
x=p[x];
else y=p[y];
}
while(x!=y){
if(level[x]>level[y])
x=father[x];
else y=father[y];
}
cout<<x<<'\n';
}
void dfs(int no){
if(level[no]<r)
p[no]=1;
else if(!(level[no]%r))
p[no]=father[no];
else p[no]=p[father[no]];
for(int i=0; i<son[1][no]; i++)
dfs(son[0][no]+i);
}
int main()
{
level[1]=0;
father[1]=0;
p[1]=1;
cin>>n>>m;
for(int i=2; i<=n; i++){
cin>>nod;
if(!son[0][nod])
son[0][nod]=i;
son[1][nod]++;
father[i]=nod;
level[i]=level[father[i]]+1;
if(level[i]>r) r=level[i];
}
r=sqrt(r);
dfs(1);
int x,y;
for(int i=1; i<=m; i++){
cin>>x>>y;
LCA(x,y);
}
return 0;
}