Pagini recente » Cod sursa (job #2273538) | Cod sursa (job #1696513) | Cod sursa (job #1624358) | Cod sursa (job #831235) | Cod sursa (job #2908415)
#include <fstream>
#include <vector>
using namespace std;
const int N = 1e5, L = 17;
int t[L][N + 1];
vector <int> fii[N + 1];
int ti[L], to[L];
int n, m, timp;
void calcul_t()
{
for (int e = 1; e <= L; e ++)
{
for (int i = 1; i <= n; i ++)
{
t[e][i] = t[e - 1][t[e - 1][i]];
}
}
}
void dfs(int x)
{
ti[x] = ++timp;
for (auto y: fii[x])
{
dfs(y);
}
to[x] = ++timp;
}
bool stramos(int x, int y)
{
return (ti[x] <= ti[y] && to[y] <= to[x]);
}
int lca(int x, int y)
{
if (stramos(x, y))
return x;
for (int e = L; e >= 0; e --)
{
if (t[e][x] != 0 && !stramos(t[e][x], y));
{
x = t[e][x];
}
}
return t[0][x];
}
int main()
{
ifstream in("lca.in");
ofstream out("lca.out");
in >> n >> m;
for (int i = 2; i <= n; i ++)
{
in >> t[0][i];
fii[t[0][i]].push_back(i);
}
calcul_t();
dfs(1);
/*
for (int i = 1; i <= L; i ++)
{
out << ti[i] << ' ';
}
out << '\n';
for (int j = 1; j <= L; j ++)
{
out << to[j] << ' ';
}
*/
for (int i = 0; i < m; i ++)
{
int x, y;
in >> x >> y;
out << lca(x, y) << '\n';
}
in.close();
out.close();
return 0;
}