Pagini recente » Cod sursa (job #687088) | Cod sursa (job #3251427) | Cod sursa (job #1162593) | Cod sursa (job #2519195) | Cod sursa (job #3169259)
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int LMAX = 100005;
int father[LMAX], str[LMAX][20], depth[LMAX];
int main() {
int n, m, i,j;
fin >> n >> m;
for (i = 2; i <= n; i++) {
fin>>father[i];
depth[i] = depth[father[i]] + 1;
str[i][0] = father[i];
}
for (j = 1; j < 20; j++) {
for (i = 1; i <= n; i++) {
//stramosul i de ord j este stramosul de ord j-1 al stramosului i de ord j-1
str[i][j] = str[str[i][j-1]][j-1];
}
}
while (m--) {
int x, y;
fin >> x >> y;
if (depth[x] < depth[y]) {
swap(x, y);
}
int p = depth[x] - depth[y];
for (j = 19; j >= 0 && p; j--) {
if ((1<<j) <= p) {
x = str[x][j];
p = p - (1<<j);
}
}
///acum x si y sunt la acelasi nivel
while (x != y) {
j = 19;
int shift = (1<<j);
while (j >= 0 && str[x][shift] == str[y][shift]) {
j--;
shift = (shift>>1);
}
x = str[x][shift];
y = str[y][shift];
}
fout<<x<<endl;
}
fin.close();
fout.close();
return 0;
}