Pagini recente » Cod sursa (job #627940) | Cod sursa (job #1710167) | Cod sursa (job #1944083) | Cod sursa (job #1380339) | Cod sursa (job #2365619)
#include <bits/stdc++.h>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int MOD = 317;
vector<int> v[100005];
int niv[100005], tmare[100005], t[100005];
int n, nrq;
void DFS(int nod, int ant, int nivel)
{
niv[nod] = nivel;
tmare[nod] = ant;
if (nivel % MOD == 0) ant = nod;
for (int i = 0;i < v[nod].size();++i)
{
DFS(v[nod][i], ant, nivel + 1);
}
}
int main()
{
in>>n>>nrq;
for (int i = 2;i <= n;++i)
{
in>>t[i];
v[t[i]].push_back(i);
}
DFS(1, 0, 0);
while (nrq--)
{
int x,y;
in>>x>>y;
while (tmare[x] != tmare[y])
{
if (niv[x] > niv[y]) x = tmare[x];
else y = tmare[y];
}
while (x != y)
{
if (niv[x] > niv[y]) x = t[x];
else y = t[y];
}
out<<x<<"\n";
}
return 0;
}