Pagini recente » Cod sursa (job #1058730) | Cod sursa (job #1631331) | Cod sursa (job #2230488) | Cod sursa (job #1828137) | Cod sursa (job #932368)
Cod sursa(job #932368)
#include<stdio.h>
#include<math.h>
#include<vector>
using namespace std;
#define nmax 100005
long i, n, m, h, hac, x, y, ii;
long niv[nmax], t[nmax], t2[nmax];
vector <long> ma[nmax];
void citire()
{
scanf("%ld %ld",&n,&m);
for (i=2;i<=n;i++)
{
scanf("%ld",&t[i]);
ma[t[i]].push_back(i);
}
}
void dfs(long nod)
{
vector <long> ::iterator it;
hac++; niv[nod]=hac;
if (hac>h)
h=hac;
for (it=ma[nod].begin();it!=ma[nod].end();it++)
dfs(*it);
hac--;
}
void dfs1(long nod, long n1)
{
vector <long> ::iterator it;
t2[nod]=n1;
if (niv[nod]%h==1)
n1=nod;
for (it=ma[nod].begin();it!=ma[nod].end();it++)
dfs1(*it,n1);
}
long lca()
{
while (t2[x]!=t2[y])
if (niv[x]>niv[y])
x=t2[x];
else
y=t2[y];
while (x!=y)
if (niv[x]>niv[y])
x=t[x];
else
y=t[y];
return x;
}
int main()
{
freopen("lca.in","r",stdin);
freopen("lca.out","w",stdout);
citire();
dfs(1);
h=long(sqrt(h))+1;
dfs1(1,1);
for (ii=1;ii<=m;ii++)
{
scanf("%ld %ld",&x,&y);
printf("%ld\n",lca());
}
return 0;
}