Pagini recente » Cod sursa (job #1901912) | Cod sursa (job #118929) | Cod sursa (job #1179279) | Cod sursa (job #2932088) | Cod sursa (job #3041968)
///dp[i][j] ->(1 << j) stramos al lui i
#include <fstream>
#include <vector>
using namespace std;
ifstream cin ("lca.in");
ofstream cout ("lca.out");
const int N = 1e5;
int dp[N + 1][18], lg[N + 1], nivel[N + 1];
vector <int> g[N + 1];
int n, m, x, y;
void dfs (int node, int parent)
{
for (auto it : g[node])
if (it != parent)
nivel[it] = nivel[node] + 1, dfs (it, node);
}
int lca (int x, int y)
{
///EGALARE nivel
if (nivel[x] < nivel[y])
swap(x, y);
for (int i = lg[nivel[x]]; i >= 0; --i)
if (nivel[dp[x][i]] >= nivel[y])
x = dp[x][i];
if (x == y)
return x;
for (int i = lg[nivel[x]]; i >= 0; --i)
if (dp[x][i] != dp[y][i])
{
x = dp[x][i];
y = dp[y][i];
}
return dp[x][0];
}
int main()
{
cin >> n >> m;
for (int i = 2; i <= n; ++i)
cin >> dp[i][0], lg[i] = lg[i >> 1] + 1, g[dp[i][0]].push_back(i);
for (int j = 1; j <= lg[n]; ++j)
for (int i = 1; i <= n; ++i)
dp[i][j] = dp[dp[i][j - 1]][j - 1];
dfs (1, -1);
for (int i = 1; i <= m; ++i)
{
cin >> x >> y;
cout << lca (x, y) << '\n';
}
return 0;
}