Pagini recente » Cod sursa (job #711325) | Monitorul de evaluare | Istoria paginii runda/simulare_oni_11-12/clasament | Istoria paginii runda/fdsfdsfds/clasament | Cod sursa (job #1991140)
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stack>
#include <vector>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
#define ll long long
#define pb push_back
const int inf = 1e9 + 5;
const int NMax = 1e5 + 5;
int N,M,H,root;
int dad[NMax],depth[NMax],an[NMax];
vector<int> v[NMax];
void dfs(int);
void build(int);
int query(int,int);
int main() {
in>>N>>M;
for (int i=2;i <= N;++i) {
in>>dad[i];
v[dad[i]].pb(i);
}
dfs(1);
for (root=1;root * root <= H;++root) ;
--root;
build(1);
while (M--) {
int a,b;
in>>a>>b;
out<<query(a,b)<<'\n';
}
in.close();out.close();
return 0;
}
void dfs(int node) {
depth[node] = depth[dad[node]] + 1;
H = max(H,depth[node]);
for (auto nxt : v[node]) {
if (depth[nxt]) {
continue;
}
dfs(nxt);
}
}
void build(int node) {
if (depth[node] % root == 1) {
an[node] = dad[node];
}
else {
an[node] = an[dad[node]];
}
for (auto nxt : v[node]) {
if (an[nxt]) {
continue;
}
build(nxt);
}
}
int query(int x,int y) {
while (an[x] != an[y]) {
if (depth[x] > depth[y]) {
x = an[x];
}
else {
y = an[y];
}
}
while (x != y) {
if (depth[x] > depth[y]) {
x = dad[x];
}
else {
y = dad[y];
}
}
return x;
}