Pagini recente » Cod sursa (job #1356998) | Cod sursa (job #2565316) | Cod sursa (job #1491153) | Monitorul de evaluare | Cod sursa (job #2084611)
#include <fstream>
#include <cmath>
#include <vector>
#define MAXN 100005
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
vector <int> graph[MAXN];
int pre[MAXN], pre2[MAXN], n, m, niv[MAXN];
int rad;
inline void DFS(int nod, int tata) {
if (niv[nod] % rad == 1)
tata = nod;
else {
pre2[nod] = tata;
}
for (auto x : graph[nod]) {
niv[x] = niv[nod] + 1;
DFS(x, tata);
}
}
inline int LCA(int x, int y) {
int a = niv[x];
int b = niv[y];
if (x == pre[y])
return x;
if (y == pre[x])
return y;
while (a > b) {
if (pre2[x] != 0) {
x = pre2[x];
}
else {
x = pre[x];
}
a = niv[x];
}
while (b > a) {
if (pre2[y] != 0) {
y = pre2[y];
}
else {
y = pre[y];
}
b = niv[y];
}
while (pre[x] != pre[y]) {
x = pre[x];
y = pre[y];
}
return pre[x];
}
inline void Read() {
fin >> n >> m;
rad = sqrt((float)n);
int t = 0, x, y;
for (int i = 2; i <= n; i++) {
fin >> x;
pre[i] = x;
graph[x].push_back(i);
}
niv[1] = 1;
DFS(1, 0);
/*for (int i = 1; i <= n; i++) {
fout << niv[i] << " ";
}
fout << "\n"; */
for (int i = 1; i <= m; i++) {
fin >> x >> y;
fout << LCA(x, y) << "\n";
}
}
int main () {
Read();
fin.close(); fout.close(); return 0;
}