Pagini recente » Cod sursa (job #2509339) | Cod sursa (job #2393093) | Cod sursa (job #160060) | Cod sursa (job #1334813) | Cod sursa (job #3285717)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin ("lca.in");
ofstream cout ("lca.out");
const int N = 1e5;
int dp[N + 1][20], dist[N + 1];
vector <int> g[N + 1];
int n, m, x, y;
int lca (int x, int y)
{
if (dist[x] < dist[y])
swap(x, y);
if (dist[x] != dist[y])
{
int dif = dist[x] - dist[y];
for (int i = 0; (1 << i) <= dif; ++i)
if ((1 << i) & dif)
x = dp[x][i];
}
if (x == y)
return x;
for (int i = __lg(dist[x]); i >= 0; --i)
if (dp[x][i] != dp[y][i])
x = dp[x][i], y = dp[y][i];
return dp[x][0];
}
void dfs (int node, int tata)
{
dist[node] = dist[tata] + 1;
for (auto it : g[node])
dfs (it, node);
}
int main()
{
cin >> n >> m;
for (int i = 2; i <= n; ++i)
cin >> dp[i][0], g[dp[i][0]].push_back(i);
for (int j = 1; (1 << j) <= 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;
}