Pagini recente » Cod sursa (job #1233493) | Cod sursa (job #3258517) | Cod sursa (job #842699) | Cod sursa (job #150755) | Cod sursa (job #3004279)
#include <fstream>
#include <vector>
using namespace std;
ifstream in ("lca.in");
ofstream out ("lca.out");
const int max_size = 1e5 + 1, rmax = 18;
int t[rmax][max_size], lg[max_size], lvl[max_size];
vector <int> mc[max_size];
void dfs (int nod)
{
for (auto f : mc[nod])
{
lvl[f] = lvl[nod] + 1;
dfs(f);
}
}
int anc (int x, int ord)
{
int e = 0;
while (ord > 0)
{
if (ord % 2 == 1)
{
x = t[e][x];
}
e++;
ord /= 2;
}
return x;
}
int lca (int x, int y)
{
int e = lg[lvl[x]];
while (e >= 0)
{
if (t[e][x] != t[e][y])
{
x = t[e][x];
y = t[e][x];
}
e--;
}
return t[0][x];
}
int main ()
{
lvl[1] = 1;
int n, q;
in >> n >> q;
for (int i = 2; i <= n; i++)
{
lg[i] = lg[i / 2] + 1;
in >> t[0][i];
mc[t[0][i]].push_back(i);
}
dfs(1);
while (q--)
{
int x, y;
in >> x >> y;
if (lvl[x] > lvl[y])
{
swap(x, y);
}
y = anc(y, lvl[y] - lvl[x]);
if (y == x)
{
out << x << '\n';
}
else
{
out << lca(x, y) << '\n';
}
}
in.close();
out.close();
return 0;
}