Pagini recente » Istoria paginii runda/fewfewd | Cod sursa (job #824961) | Statistici Justin Andrei (Justinelu1998) | Cod sursa (job #1081373) | Cod sursa (job #2512985)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 50;
ifstream fin("lca.in");
ofstream fout("lca.out");
vector <int> g[MAXN];
int father[MAXN];
int dist[MAXN];
bool seen[MAXN];
void dfs(int node, int papa){
if(seen[node]) return;
seen[node] = true;
dist[node] = dist[papa] + 1;
for(auto x : g[node]){
if(!seen[x]) dfs(x, node);
}
}
void nivel(int &x, int &y){
if(dist[y] > dist[x]) swap(x, y);
while(x and y and dist[x] > dist[y]) x = father[x];
}
int rez(int x, int y){
while(x and y and x != y) x = father[x], y = father[y];
return x;
}
int main() /// REZ O(N * 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[i + 1]= x;
}
dfs(1, 0);
for(int i = 1; i <= m; ++i){
int x, y; fin >> x >> y;
nivel(x, y);
fout << rez(x, y) << '\n';
}
return 0;
}