Pagini recente » Cod sursa (job #536994) | Cod sursa (job #2917185) | Cod sursa (job #2608702) | Cod sursa (job #1349310) | Cod sursa (job #2897107)
#include <fstream>
#include <queue>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
int n,t[100001],niv[100001];
bool ver[101];
int main()
{
int m;
in>>n>>m;
for(int i=2 ; i<=n ; i++)
in>>t[i];
{
//bfs
queue <int> q;
q.push(1);
while(!q.empty())
{
int nod=q.front();
q.pop();
for(int i=1 ; i<=n ; i++)
if(t[i]==nod)
{
niv[i]=niv[nod]+1;
q.push(i);
}
}
}
while(m)
{
int a,b;
in>>a>>b;
while(a!=b)
{
if(niv[a]<niv[b])
b=t[b];
else a=t[a];
}
out<<a<<"\n";
m--;
}
return 0;
}