Pagini recente » Cod sursa (job #2208548) | Cod sursa (job #1622919) | Cod sursa (job #2001632) | Cod sursa (job #60949) | Cod sursa (job #2392254)
#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], ancestor[100001];
vector <int> Muchii[100001];
inline void DFS(int nod, int prev, int nivel)
{
int vecin;
l[nod] = nivel;
ancestor[nod] = prev;
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 (ancestor[x] != ancestor[y])
{
if (l[x] > l[y])
x = ancestor[x];
else
y = ancestor[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;
}