Pagini recente » Cod sursa (job #1039808) | Cod sursa (job #2263951) | Cod sursa (job #3032765) | Cod sursa (job #2525718) | Cod sursa (job #2776021)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("lca.in");
ofstream fout ("lca.out");
void usain_bolt()
{
ios::sync_with_stdio(false);
fin.tie(0);
}
const int N = 1e5 + 5;
int tour[4 * N], rmq[22][4 * N], lg[4 * N], first[N], height[N];
bool f[N];
vector < int > a[N];
void dfs(int k, int dad = 0)
{
f[k] = true;
first[k] = ++tour[0];
height[k] = height[dad] + 1;
tour[tour[0]] = k;
for(auto v : a[k]) {
if(f[v] == false) {
dfs(v, k);
tour[++tour[0]] = k;
}
}
}
int main()
{
usain_bolt();
int n, m;
fin >> n >> m;
for(int i = 1; i < n; ++i) {
int x;
fin >> x;
a[x].push_back(i + 1);
a[i + 1].push_back(x);
}
dfs(1);
for(int i = 1; i <= tour[0]; ++i) {
rmq[0][i] = tour[i];
}
for(int i = 2; i <= tour[0]; ++i) {
lg[i] = lg[i >> 1] + 1;
}
for(int i = 1; (1 << i) <= tour[0]; ++i) {
for(int j = 1; j + (1 << i) - 1 <= tour[0]; ++j) {
if(height[rmq[i - 1][j]] < height[rmq[i - 1][j + (1 << (i - 1))]]) {
rmq[i][j] = rmq[i - 1][j];
}
else {
rmq[i][j] = rmq[i - 1][j + (1 << (i - 1))];
}
}
}
for(; m; --m) {
int x, y, xx, yy;
fin >> x >> y;
xx = x, yy = y;
x = first[x], y = first[y];
if(x > y) {
swap(x, y);
}
int dif = y - x + 1;
int base = lg[dif];
if(height[rmq[base][x]] < height[rmq[base][y - (1 << base) + 1]]) {
fout << rmq[base][x] << "\n";
}
else {
fout << rmq[base][y - (1 << base) + 1] << "\n";
}
}
return 0;
}