Pagini recente » Cod sursa (job #194309) | Cod sursa (job #2661426) | Cod sursa (job #265423) | minus | Cod sursa (job #3231819)
#include <fstream>
#include <vector>
using namespace std;
const int N = 1e5;
const int L = 16;
int t_in[N+1], t_out[N+1], s[L+1][N+1], n, timp;
vector <int> fii[N+1];
void constructie_s()
{
for (int i = 1; (1 << i) <= n; i++)
{
for (int j = 1; j <= n; j++)
{
s[i][j] = s[i-1][s[i-1][j]];
}
}
}
void dfs(int x)
{
t_in[x] = ++timp;
for (auto y: fii[x])
{
dfs(y);
}
t_out[x] = ++timp;
}
bool este_stramos(int x, int y)
{
return (t_in[x] <= t_in[y] && t_out[y] <= t_out[x]);
}
int lca(int x, int y)
{
///cautam cel mai de sus (de pe cel mai mic nivel) stramos al lui x care NU e stramos al lui y
if (este_stramos(x, y))
{
return x;
}
int pas = L;
while (pas >= 0)
{
if (s[pas][x] != 0 && !este_stramos(s[pas][x], y))
{
x = s[pas][x];
}
pas--;
}
return s[0][x];///tatal celui mai indepartat stramos al lui x initial care NU e stramos pentru y
}
int main()
{
ifstream in("lca.in");
ofstream out("lca.out");
int q;
in >> n >> q;
for (int j = 2; j <= n; j++)
{
in >> s[0][j];
fii[s[0][j]].push_back(j);
}
timp = 0;
dfs(1);
for (int i = 0; i < q; i++)
{
int x, y;
in >> x >> y;
out << lca(x, y) << "\n";
}
in.close();
out.close();
return 0;
}