Pagini recente » Cod sursa (job #3181742) | Cod sursa (job #2873613) | Cod sursa (job #2319132) | Cod sursa (job #2319133) | Cod sursa (job #2900923)
#include <bits/stdc++.h>
using namespace std;
const long long NR = 2e5 + 1;
int d[NR], parent[NR], lvl[NR], eulerTour[NR << 1], lg[NR << 1], firstAp[NR], n, m, eulerCounter;
int rmq[20][NR];
vector<int> v[NR];
const int oo = 1e9;
void dfs(int nod, int prt) {
eulerTour[++eulerCounter] = nod;
firstAp[nod] = eulerCounter;
parent[nod] = prt;
lvl[nod] = 1 + lvl[prt];
for (auto it : v[nod]) {
if (it == prt) {
continue;
}
dfs(it, nod);
eulerTour[++eulerCounter] = nod;
}
}
void compute() {
for (int i = 1; i <= eulerCounter; ++i) {
i > 1 ? lg[i] = 1 + lg[i >> 1] : int();
rmq[0][i] = eulerTour[i];
}
for (int i = 1; (1 << i) <= eulerCounter; ++i) {
for (int j = 1; j + (1 << i) <= eulerCounter + 1; ++j) {
rmq[i][j] = (lvl[rmq[i - 1][j]] < lvl[rmq[i - 1][j + (1 << (i - 1))]]) ? rmq[i - 1][j] : rmq[i - 1][j + (1
<< (i - 1))];
}
}
}
int lcaQuery(int x, int y) {
x = firstAp[x];
y = firstAp[y];
x > y ? swap(x, y) : void();
int logg = lg[y - x + 1];
return lvl[rmq[logg][x]] < lvl[rmq[logg][y - (1 << logg) + 1]] ? rmq[logg][x] : rmq[logg][y - (1 << logg) + 1];
}
ifstream in("lca.in");
ofstream out("lca.out");
signed main() {
ios::sync_with_stdio(false);
in.tie();
int x, y;
in >> n >> m;
for (int i = 1; i < n; ++i) {
in >> y;
x = i + 1;
v[x].emplace_back(y);
v[y].emplace_back(x);
}
dfs(1, 0);
compute();
for (int i = 1; i <= m; ++i) {
in >> x >> y;
out << lcaQuery(x, y) << '\n';
}
return 0;
}