Pagini recente » Cod sursa (job #369259) | Cod sursa (job #2337274) | Cod sursa (job #1581397) | Cod sursa (job #2767206) | Cod sursa (job #2084562)
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
int n,m,a[100003],niv[100003];
int nv(int i)
{
int c=0;
while(a[i]!=0)
{
c++;
i=a[i];
}
return c+1;
}
void par(int x,int y)
{
while(niv[x]!=niv[y])
{
if(niv[x]>niv[y])
{
x=a[x];
}
else
if(niv[x]<niv[y])
y=a[y];
}
while(x!=y)
{
x=a[x];
y=a[y];
}
out<<x<<endl;
}
int main()
{
in>>n>>m;
int x,y;
for(int i=2;i<=n;i++)
in>>a[i];
for(int i=1;i<=n;i++)
{
niv[i]=nv(i);
//out<<niv[i]<<' ';
}
for(int i=0;i<m;i++)
{
in>>x>>y;
par(x,y);
}
return 0;
}