Pagini recente » Cod sursa (job #160119) | Cod sursa (job #1911466) | Cod sursa (job #2819980) | Cod sursa (job #1998672) | Cod sursa (job #2392252)
#include <bits/stdc++.h>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int SIZE = 320;
int n, m, v[100001];
int l[100001], father[100001];
vector <int> Muchii[100001];
inline void DFS(int nod, int prev, int nivel)
{
int vecin;
l[nod] = nivel;
if (nivel % SIZE == 0)
prev = nod;
for (int i = 0; i < Muchii[nod].size(); ++i)
{
vecin = Muchii[nod][i];
DFS(vecin, nod, nivel + 1);
}
}
inline void citire()
{
int x;
in >> n >> m;
for (int i = 2; i <= n; ++i)
{
in >> father[i];
Muchii[father[i]].push_back(i);
}
}
inline int lca(int x, int y)
{
while (father[x] != father[y])
{
if (l[x] > l[y])
x = father[x];
else
y = father[y];
}
while (x != y)
{
if (l[x] > l[y])
x = father[x];
else
y = father[y];
}
return x;
}
int main()
{
int x, y;
citire();
DFS(1, 0, 0);
for (int q = 1; q <= m; ++q)
{
in >> x >> y;
out << lca(x, y) << '\n';
}
return 0;
}