Pagini recente » Istoria paginii info-oltenia-2019/echipe/clasament/11-12 | Cod sursa (job #193681) | Cod sursa (job #664252) | Cod sursa (job #3181930) | Cod sursa (job #2629036)
#include <bits/stdc++.h>
using namespace std;
#define NMAX 100005
FILE *_fin;
int _in_loc; char _in_buff[4096];
void read_init(const char* nume){
_fin = fopen(nume, "r");
_in_loc = 4095;
}
char read_ch()
{
++_in_loc;
if (_in_loc == 4096) {
_in_loc = 0;
fread(_in_buff, 1, 4096, _fin);
}
return _in_buff[_in_loc];
}
int read_u32()
{
int u32 = 0; char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-') {
sgn = -1;
} else {
u32 = c - '0';
}
while (isdigit(c = read_ch())) {
u32 = u32 * 10 + c - '0';
}
return u32 * sgn;
}
int n, m, father[NMAX], depth[NMAX];
int find_lca(int x, int y) {
while(x != y) {
if(depth[x] > depth[y]) {
x = father[x];
} else {
y = father[y];
}
}
return x;
}
int main() {
read_init("lca.in");
freopen("lca.out", "w", stdout);
n = read_u32();
m = read_u32();
for(int i = 2; i <= n; i++) {
father[i] = read_u32();
depth[i] = depth[father[i]] + 1;
}
for(int i = 1; i <= m; i++) {
int x, y;
x = read_u32(), y = read_u32();
printf("%d\n", find_lca(x, y));
}
return 0;
}