Pagini recente » Cod sursa (job #2894829) | Cod sursa (job #2797939) | Cod sursa (job #2058039) | Cod sursa (job #2870872) | Cod sursa (job #2145271)
#include <bits/stdc++.h>
using namespace std;
#if 1
#define pv(x) cout<<#x<<" = "<<x<<"; ";cout.flush()
#define pn cout<<endl
#else
#define pv(x)
#define pn
#endif
#ifdef ONLINE_JUDGE
#define in cin
#define out cout
#else
ifstream in("lca.in");
ofstream out("lca.out");
#endif
using ll = long long;
using ull = unsigned long long;
using ui = unsigned int;
#define pb push_back
#define mp make_pair
const int NMax = 1e5 + 5;
const ll inf_ll = 1e18 + 5;
const int inf_int = 1e9 + 5;
const int mod = 100003;
using zint = int;
int N,M,height,root;
int depth[NMax],dad[NMax],an[NMax];
vector<int> v[NMax];
void getHeight(int node) {
for (int nxt : v[node]) {
if (nxt == dad[node]) {
continue;
}
depth[nxt] = depth[node] + 1;
getHeight(nxt);
}
height = max(height, depth[node]);
}
void build(int node) {
an[node] = (depth[node] % root == 0) ? dad[node] : an[dad[node]];
for (int nxt : v[node]) {
if (nxt == dad[node]) {
continue;
}
build(nxt);
}
}
int main() {
in>>N>>M;
for (int i = 2;i <= N;++i) {
in>>dad[i];
v[dad[i]].pb(i);
}
getHeight(1);
for(root = 1;root*root <= height;++root) ;
--root;
build(1);
while (M--) {
int x,y;
in>>x>>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];
}
}
out<<x<<'\n';
}
return 0;
}