Pagini recente » Cod sursa (job #1794376) | Statistici Irina Cristali (Irina.Cristali) | Cod sursa (job #1796169) | Cod sursa (job #1245863) | Cod sursa (job #2862196)
#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);
}
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 i = 1; i <= N; i++) {
for(int j = 1; j < LOG; j++) {
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;
}