Pagini recente » Cod sursa (job #1758739) | Cod sursa (job #731133) | Cod sursa (job #123112) | Cod sursa (job #1494498) | Cod sursa (job #3170852)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int maxn = 1e5 + 2;
set<int> s;
int t[maxn], n, m, timer;
vector<int> a[maxn + 2];
int nivel[maxn + 2];
int poz[maxn + 2];
int e[2 * maxn + 2];
int lg[100005];
int r[20][2 * maxn];
void read(){
fin >> n >> m;
t[1] = 1;
for(int i = 2; i <= n; ++i){
int x; fin >> x;
t[i] = x;
a[x].push_back(i);
}
}
void dfs(int i){
nivel[i] = nivel[t[i]] + 1;
e[++timer] = i;
poz[i] = timer;
for(auto x : a[i]){
dfs(x);
e[++timer] = i;
}
}
void precalculate(){
lg[0] = -1;
for(int i = 1; i <= timer; ++i){
lg[i] = lg[i >> 1] + 1;
r[0][i] = e[i];
}
for(int i = 1; (1 << i) <= timer; ++i){
for(int j = (1 << i); j <= timer; ++j){
r[i][j] = r[i - 1][j];
if(nivel[r[i - 1][j - (1 << (i - 1))]] < nivel[r[i - 1][j]])
r[i][j] = r[i - 1][j - (1 << (i - 1))];
}
}
}
int lca(int x, int y){
int left = poz[x];
int right = poz[y];
if(left > right)
swap(left, right);
int len = lg[right - left + 1];
x = r[len][left + (1 << len)];
y = r[len][right];
if(nivel[y] < nivel[x])
x = y;
return x;
}
int main(){
read();
dfs(1);
precalculate();
for(int i = 1; i <= m; ++i){
int x, y;
fin >> x >> y;
fout << lca(x, y) << "\n";
}
return 0;
}
/*
r[i][j] = nodul care se afla pe nivelul minim in arbore, din secventa de lungime 2^i si care se termina
pe pozitia j
*/