Pagini recente » Cod sursa (job #484980) | Cod sursa (job #468041) | Cod sursa (job #170219) | Cod sursa (job #1476751) | Cod sursa (job #2028159)
#include <fstream>
#include <vector>
// SOLUTIA 1 - BRUT
using namespace std;
const int Maxn = 1e5 + 1e4;
ifstream cin("lca.in");
ofstream cout("lca.out");
int tata[Maxn];
int nivel[Maxn];
vector <int> gr[Maxn];
void dfs(int node, int boss, int lvl){
nivel[node] = lvl;
for(int x : gr[node]){
if(x == boss) continue;
dfs(x, node, lvl+1);
}
}
int solve(int x, int y){
if(nivel[x] < nivel[y]) swap(x, y);
while(nivel[x] > nivel[y]) x = tata[x];
while(x != y) x = tata[x], y = tata[y];
return x;
}
int main(){
int n, m;
cin >> n >> m;
tata[1] = 0;
for(int i = 2; i <= n; ++ i){
cin >> tata[i];
gr[i].push_back(tata[i]);
gr[tata[i]].push_back(i);
}
dfs(1, 0, 1);
for(int i = 1; i <= m; ++ i){
int x, y;
cin >> x >> y;
cout << solve(x, y) << '\n';
}
return 0;
}