Pagini recente » Cod sursa (job #1034351) | Cod sursa (job #2332979) | Cod sursa (job #2956525) | Cod sursa (job #1488069) | Cod sursa (job #2486139)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int nmax = 100000;
vector <int> g[nmax + 5];
int tt[nmax + 5], n, m, lev[nmax + 5];
void Read(){
fin >> n >> m;
for (int i = 2; i <= n; i++){
fin >> tt[i];
g[tt[i]].push_back(i);
}
}
void CalcLevel(int nod){
lev[nod] = lev[tt[nod]] + 1;
for (auto i : g[nod])
if (!lev[i])
CalcLevel(i);
}
int LCA(int x, int y){
if (lev[x] > lev[y])
swap(x, y);
while (lev[y] != lev[x])
y = tt[y];
while (x != y){
x = tt[x];
y = tt[y];
}
return x;
}
void Print(){
while(m--){
int x, y;
fin >> x >> y;
fout << LCA(x, y) << '\n';
}
}
int main(){
Read();
CalcLevel(1);
Print();
return 0;
}