Pagini recente » Rezultatele filtrării | Cod sursa (job #2767032) | Borderou de evaluare (job #1750147) | Cod sursa (job #530901) | Cod sursa (job #2771411)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int mxN = 1e5 + 5, mxLOG = 17;
int up[mxN][mxLOG], depth[mxN];
vector<int> fiu[mxN];
void dfs(int x) {
for (int vecin : fiu[x]) {
if (depth[vecin] == 0) {
depth[vecin] = depth[x] + 1;
dfs(vecin);
}
}
}
int main() {
ios::sync_with_stdio(false), fin.tie(nullptr), fout.tie(nullptr);
int n, m; fin >> n >> m;
for (int i = 1; i < n; ++i) {
fin >> up[i + 1][0];
fiu[up[i + 1][0]].push_back(i + 1);
}
depth[1] = 1;
dfs(1);
for (int j = 1; j < mxLOG; ++j) {
for (int i = 1; i <= n; ++i) {
up[i][j] = up[up[i][j - 1]][j - 1];
}
}
while (m--) {
int x, y; fin >> x >> y;
if (depth[y] > depth[x]) {
swap(x, y);
}
int length = depth[x] - depth[y];
for (int i = 31; i >= 0; --i) {
if ((length & (1 << i))) {
x = up[x][i];
}
}
if (x == y) {
fout << x << '\n';
continue;
}
for (int i = 16; i >= 0; --i) {
if (up[x][i] != up[y][i]) {
x = up[x][i];
y = up[y][i];
}
}
fout << up[x][0] << '\n';
}
return 0;
}