Pagini recente » Cod sursa (job #2966031) | Cod sursa (job #702579) | Cod sursa (job #427831) | Cod sursa (job #1047592) | Cod sursa (job #2149019)
#include <bits/stdc++.h>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
const int nMax = 100005;
int dp[23][nMax], nv[nMax];
vector <int> G[nMax];
bool viz[nMax];
inline void Nivel(int nod, int niv) {
viz[nod] = true;
nv[nod] = niv;
for(const auto &v : G[nod]) {
if(!viz[v]) {
Nivel(v, niv + 1);
}
}
}
inline int Stramos(int x, int y) { ///al y-lea stramos al lui x
int p = x;
for(int i = 0; i <= 20; i++) {
if(y & (1 << i)) {
p = dp[i][p];
}
}
return p;
}
inline int Lca(int x, int y) {
if(nv[y] > nv[x]) {
swap(x, y);
}
x = Stramos(x, nv[x] - nv[y]);
if(x == y) {
return x;
}
for(int i = 20; i >= 0; i--){
if(dp[i][x] != dp[i][y]) {
x = dp[i][x];
y = dp[i][y];
}
}
return dp[0][x];
}
int main()
{
int n, m, x, y;
f >> n >> m;
for(int i = 2; i <= n; i++) {
f >> x;
dp[0][i] = x;
G[x].push_back(i);
}
for(int i = 1; (1 << i) <= n; i++) {
for(int j = 1; j <= n; j++) {
dp[i][j] = dp[i - 1][dp[i - 1][j]];
}
}
Nivel(1, 0);
for(int i = 1; i <= m; i++) {
f >> x >> y;
g << Lca(x, y) << "\n";
}
return 0;
}