Pagini recente » Atasamentele paginii Profil TudorN | Statistici Nechifor Tudor-Mihail (TudorN) | Statistici Amza A (amza23) | Statistici Dinu Marius Valentin (Konnay) | Cod sursa (job #3364985)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int NMAX = 1e5;
const int LOGMAX = 20;
vector <int> adj[NMAX + 1];
int dp[NMAX + 1][LOGMAX + 1];
int lvl[NMAX + 1];
void dfs(int node, int par){
dp[node][0] = par;
lvl[node] = lvl[par] + 1;
for(int vec : adj[node]){
if(vec != par){
dfs(vec, node);
}
}
}
int LCA(int a, int b){
if(lvl[a] < lvl[b]){
swap(a, b);
}
int diff = lvl[a] - lvl[b];
for(int j = LOGMAX; j >= 0; j--){
if(diff & (1 << j)){
a = dp[a][j];
}
}
if(a == b){
return a;
}
for(int j = LOGMAX; j >= 0; j--){
if(dp[a][j] != dp[b][j]){
a = dp[a][j];
b = dp[b][j];
}
}
return dp[a][0];
}
ifstream fin("lca.in");
ofstream fout("lca.out");
int main(){
int n, m;
fin >> n >> m;
for(int i = 2; i <= n; i++){
int x;
fin >> x;
adj[x].push_back(i);
adj[i].push_back(x);
}
dfs(1, 0);
for(int j = 1; j <= LOGMAX; j++){
for(int i = 1; i <= n; i++){
dp[i][j] = dp[dp[i][j - 1]][j - 1];
}
}
while(m --){
int a, b;
fin >> a >> b;
fout << LCA(a, b) << '\n';
}
return 0;
}