Pagini recente » Cod sursa (job #466696) | Cod sursa (job #1419234) | Cod sursa (job #807330) | Cod sursa (job #3032498) | Cod sursa (job #2908418)
#include <fstream>
#include <vector>
using namespace std;
ifstream in ("lca.in");
ofstream out ("lca.out");
const int max_size = 1e5 + 1, rmax = 17;
int t[rmax][max_size], ti[max_size], to[max_size], n, timp;
vector <int> edges[max_size];
int lca (int x, int y)
{
if (ti[x] <= ti[y] && to[x] >= to[y])
{
return x;
}
for (int e = rmax - 1; e >= 0; e--)
{
if (t[e][x] != 0 && !(ti[t[e][x]] <= ti[y] && to[t[e][x]] >= to[y]))
{
x = t[e][x];
}
}
return t[0][x];
}
void dfs (int nod)
{
ti[nod] = ++timp;
for (auto f : edges[nod])
{
dfs(f);
}
to[nod] = ++timp;
}
int main ()
{
int n, q;
in >> n >> q;
for (int i = 2; i <= n; i++)
{
in >> t[0][i];
edges[t[0][i]].push_back(i);
}
for (int e = 1; e < rmax; e++)
{
for (int i = 1; i <= n; i++)
{
t[e][i] = t[e - 1][t[e - 1][i]];
}
}
dfs(1);
while (q--)
{
int x, y;
in >> x >> y;
out << lca(x, y) << '\n';
}
in.close();
out.close();
return 0;
}