Pagini recente » Cod sursa (job #1153284) | Cod sursa (job #2754878) | Cod sursa (job #755088) | Cod sursa (job #1323992) | Cod sursa (job #2513028)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 50;
const int LOGMAX = 20 + 4;
ifstream fin("lca.in");
ofstream fout("lca.out");
vector <int> g[MAXN];
int father[LOGMAX][MAXN];
int dist[MAXN];
void dfs(int node, int papa){
dist[node] = dist[papa] + 1;
for(auto x : g[node]){
if(x != papa) dfs(x, node);
}
}
void rezolvare(int x, int y){
for(int i = LOGMAX - 4; i >= 0; --i){
if(father[i][x] != father[i][y])
x = father[i][x], y = father[i][y];
}
fout << father[0][x] << '\n';
}
void initializare(int n){
for(int x = 1; x <= LOGMAX - 4; ++x)
for(int i = 1; i <= n; ++i)
father[x][i] = father[x - 1][father[x - 1][i]];
}
int main() /// REZ O(N * log(N) + M * log(M))
{
ios::sync_with_stdio(false);
fin.tie(0); fout.tie(0);
int n, m; fin >> n >> m;
for(int i = 1; i < n; ++i){
int x ; fin >> x;
g[x].push_back(i + 1);
father[0][i + 1] = x;
}
dfs(1, 0);
//for(int i = 1; i <= n; ++i) fout << dist[i] << " ";
for(int i = 1; i <= m; ++i){
int x, y; fin >> x >> y;
if(dist[y] > dist[x]) swap(x, y);
int nivel = dist[x] - dist[y] ;
for(int i = 0; (1 << i) <= nivel; ++i)
if(nivel & (1 << i)) x = father[i][x];
if(x != y) rezolvare(x ,y);
else fout << x << '\n';
}
return 0;
}