Pagini recente » Cod sursa (job #3345161) | Cod sursa (job #3273085) | Cod sursa (job #3349591) | Cod sursa (job #945396) | Cod sursa (job #3308784)
//hld
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("lca.in");
ofstream fout ("lca.out");
const int nmax = 1e5 + 5;
vector <int> g[nmax];
int n, m, father[nmax], weight[nmax], lvl[nmax], heavy[nmax], top[nmax];
void dfs (int node)
{
weight[node] = 1;
lvl[node] = lvl[father[node]] + 1;
for (auto it : g[node])
{
dfs (it);
weight[node] += weight[it];
if (weight[it] > weight[heavy[node]])
heavy[node] = it;
}
}
void hpd (int node, int tp)
{
top[node] = tp;
if (!heavy[node])
return;
hpd (heavy[node], tp);
for (auto it : g[node])
{
if (it != heavy[node])
hpd (it, it);
}
}
int lca (int x, int y)
{
if (x > y)
swap (x, y);
while (top[x] != top[y])
{
if (lvl[top[x]] > lvl[top[y]])
x = father[top[x]];
else
y = father[top[y]];
}
if (lvl[x] < lvl[y])
return x;
return y;
}
int main ()
{
fin >> n >> m;
for (int i = 2; i <= n; i++)
{
fin >> father[i];
g[father[i]].push_back (i);
}
father[1] = 1;
dfs (1);
hpd (1, 1);
for (int i = 1; i <= m; i++)
{
int x, y;
fin >> x >> y;
fout << lca (x, y) << '\n';
}
return 0;
}