Pagini recente » Cod sursa (job #2071004) | Cod sursa (job #1686537) | Cod sursa (job #1289633) | Cod sursa (job #1991046) | Cod sursa (job #3133663)
#include <fstream>
#include <vector>
using namespace std;
const int N = 1e5;
const int L = 16;
const int INF = 1e9;
int n, t[L+1][N+1], b[L+1][N+1], t_i[N+1], t_o[N+1], timp;
vector <int> a[N+1];
void dfs(int x)
{
t_i[x] = ++timp;
for (auto y: a[x])
{
if (t_i[y] == 0)///y e fiu al lui x in arborele cu rad 1
{
t[0][y] = x;
dfs(y);
}
}
t_o[x] = ++timp;
}
void constructie_t()
{
for (int i = 1; (1 << i) <= n; i++)
{
for (int j = 1; j <= n; j++)
{
t[i][j] = t[i-1][t[i-1][j]];
}
}
}
bool este_stramos(int x, int y)
{
return (t_i[x] <= t_i[y] && t_o[y] <= t_o[x]);
}
int lca(int x, int y)
{
if (este_stramos(x, y))
{
return x;
}
int pas = L;
while (pas >= 0)
{
if (t[pas][x] != 0 && !este_stramos(t[pas][x] , y))
{
x = t[pas][x];
}
pas--;
}
return t[0][x];
}
int main()
{
ifstream in("lca.in");
ofstream out("lca.out");
int m;
in >> n >> m;
for (int i = 2; i <= n; i++)
{
in >> t[0][i];
a[t[0][i]].push_back(i);
}
dfs(1);
constructie_t();
for (int i = 0; i < m; i++)
{
int x, y;
in >> x >> y;
out << lca(x, y) << "\n";
}
in.close();
out.close();
return 0;
}