Pagini recente » Cod sursa (job #100690) | Cod sursa (job #2572413) | Cod sursa (job #1921526) | Cod sursa (job #2767867) | Cod sursa (job #3257626)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int Max = 18;
int n, q, i, tin[100002], tout[100002];
int stramos[100002][20];
vector<int> a[100002];
static inline void InitStramosii() {
for(int b = 1; b <= Max; b++) {
for(int i = 1; i <= n; i++) stramos[i][b] = stramos[stramos[i][b - 1]][b - 1];
}
}
int timp = 0;
static inline void InitTimp(int nod = 1, int last = 0) {
timp++;
tin[nod] = timp;
for(auto it : a[nod]) {
if(nod != last) InitTimp(it, nod);
}
tout[nod] = timp;
}
static inline bool IsStramos(int a, int b) {
return (tin[a] <= tin[b] && tout[a] >= tout[b]);
}
static inline int LCA(int x, int y) {
if(IsStramos(x, y)) return x;
if(IsStramos(y, x)) return y;
for(int p = Max; p >= 0; p--) {
int z = stramos[x][p];
if(z != 0 && !IsStramos(z, y)) x = z;
}
return stramos[x][0];
}
int main() {
fin >> n >> q;
for(i = 2; i <= n; i++) {
fin >> stramos[i][0];
a[stramos[i][0]].push_back(i);
}
InitStramosii();
InitTimp();
while(q--) {
int x, y;
fin >> x >> y;
fout << LCA(x, y) << "\n";
}
return 0;
}