Pagini recente » Cod sursa (job #1801504) | Cod sursa (job #858472) | Monitorul de evaluare | Cod sursa (job #819729) | Cod sursa (job #2862186)
#include <iostream>
#define NMAX 100003
#define LOG 17
using namespace std;
int N, M;
int Fathers[NMAX][LOG], depth[NMAX];
void LCA(int a, int b) {
if(depth[a] < depth[b]) {
swap(a, b);
}
if(depth[a] > depth[b]) {
int i = LOG - 1;
while(i >= 0) {
if(depth[Fathers[a][i]] >= depth[b])
a = Fathers[a][i];
i--;
}
}
if(a == b) {
printf("%d", a);
return;
} else {
int i = LOG - 1;
while(i >= 0)
{
if(Fathers[a][i] != Fathers[b][i]) {
a = Fathers[a][i];
b = Fathers[b][i];
}
i--;
}
}
printf("%d\n", Fathers[a][0]);
}
int main()
{
freopen("lca.in", "r", stdin);
freopen("lca.out", "w", stdout);
scanf("%d %d", &N, &M);
Fathers[1][0] = -1;
depth[1] = 1;
for(int i = 2; i <= N; i++) {
int f;
scanf("%d", &f);
Fathers[i][0] = f;
depth[i] = depth[Fathers[i][0]] + 1;
}
for(int j = 1; j < LOG; j++) {
for(int i = 1; i <= N; i++) {
Fathers[i][j] = Fathers[Fathers[i][j - 1]][j - 1];
}
}
for(int i = 1; i <= M; i++) {
int a, b;
scanf("%d %d", &a, &b);
LCA(a, b);
}
return 0;
}