Pagini recente » Cod sursa (job #550167) | Cod sursa (job #2209344) | Cod sursa (job #138959) | Cod sursa (job #1623352) | Cod sursa (job #2306940)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int NMAX = 100005;
vector<int> g[NMAX];
int h[NMAX], dad[NMAX];
void dfs(int node) {
for(auto it : g[node]) {
if(h[it] == 0) {
h[it] = h[node] + 1;
dad[it] = node;
dfs(it);
}
}
}
int main() {
int n, m;
in >> n >> m;
for(int i = 2; i <= n; i ++) {
int x;
in >> x;
g[x].push_back(i);
g[i].push_back(x);
}
h[1] = 1;
dfs(1);
for(int qr = 1; qr <= m; qr ++) {
int x, y;
in >> x >> y;
while(x != y) {
if(h[x] > h[y])
x = dad[x];
else
y = dad[y];
}
out << x << "\n";
}
return 0;
}