Pagini recente » Cod sursa (job #1359798) | Cod sursa (job #2493900) | Cod sursa (job #1339465) | Cod sursa (job #1587217) | Cod sursa (job #3193057)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int LMAX = 100005;
vector<int> euler, L[LMAX];
vector<bool> viz(LMAX, 0);
int rmq[2 * LMAX][22], depth[LMAX], firstpoz[LMAX], log[2*LMAX];
///rmq[i][j] este nodul cu depth-ul minim din intervalul [i, i + 2^j - 1]
void dfs(int node) {
viz[node] = true;
euler.push_back(node);
firstpoz[node] = euler.size() - 1;
for (int vec : L[node]) {
if (!viz[vec]) {
depth[vec] = depth[node] + 1;
dfs(vec);
euler.push_back(node);
}
}
}
void init(int n) {
for (int i = 2; i < n; i++) {
log[i] = log[(i>>1)] + 1;
}
}
int main() {
int n, m, i, x, j;
fin>>n>>m;
for (i = 2; i <= n; i++) {
fin>>x;
L[x].push_back(i);
}
dfs(1);
for (i = 0; i < euler.size(); i++) {
rmq[i][0] = euler[i];
}
for (j = 1; j < 21; j++) {
for (i = 0; i < euler.size(); i++) {
rmq[i][j] = rmq[i][j-1];
if (i + (1<<j) < euler.size()) {
if (depth[rmq[i][j]] > depth[rmq[i + (1<<j)][j-1]]) {
rmq[i][j] = rmq[i + (1<<j)][j-1];
}
}
}
}
init(euler.size());
int y, pmax, dif;
while (m--) {
fin>>x>>y;
if (firstpoz[x] > firstpoz[y]) swap(x, y);
pmax = log[firstpoz[y] - firstpoz[x]];
// dif = firstpoz[y] - firstpoz[x] - (1<<pmax);
if (depth[rmq[firstpoz[x]][pmax]] < depth[rmq[firstpoz[y] - (1<<pmax) + 1][pmax]]) {
fout<<rmq[firstpoz[x]][pmax];
}
else fout<<rmq[firstpoz[y] - (1<<pmax) + 1][pmax];
fout<<endl;
}
fin.close();
fout.close();
return 0;
}