Pagini recente » Cod sursa (job #3184735) | Cod sursa (job #2625858) | Cod sursa (job #1818870) | Cod sursa (job #3169858) | Cod sursa (job #3215000)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin ("lca.in");
ofstream cout ("lca.out");
const int M = 17;
const int N = 1e5;
int lg[N + 1], dp[N + 1][M + 1], h[N + 1];
int n, m, x, y;
vector <int> g[N + 1];
void dfs (int node, int parent)
{
h[node] = h[parent] + 1;
for (auto it : g[node])
if (it != parent)
dfs (it, node);
}
int lca (int x, int y)
{
if (h[x] < h[y])
swap(x, y);
for (int i = lg[h[x]]; i >= 0; --i)
if (h[x] - (1 << i) >= h[y]) x = dp[x][i];
if (x == y)return x;
for (int i = lg[h[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 = 1; i < n; ++i)
g[(dp[i + 1][0] = (cin >> x, x))].push_back(i + 1);///ce dracu e asta
for (int i = 2; i <= n; ++i)
lg[i] = lg[i >> 1] + 1;
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, 0);
for (int i = 1; i <= m; ++i)
{
cin >> x >> y;
cout << lca (x, y) << '\n';
}
return 0;
}