Pagini recente » Cod sursa (job #1402046) | Profil el_nucu | Profil loredana | Istoria paginii runda/ada13/clasament | Cod sursa (job #2017249)
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <deque>
#include <ctime>
#include <queue>
#define ll long long
#define ull unsigned long long
#define pb push_back
using zint = int;
using namespace std;
const int inf = 1e9 + 5;
const int NMax = 1e5 + 5;
ifstream in("lca.in");
ofstream out("lca.out");
int N,M,H,root;
int depth[NMax],dad[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);
root = 1;
while (root * root <= H) {
++root;
}
--root;
build(1);
while (M--) {
int x,y;
in>>x>>y;
out<<query(x,y)<<'\n';
}
in.close();out.close();
return 0;
}
void dfs(int node) {
depth[node] = depth[dad[node]] + 1;
for (int nxt : v[node]) {
dfs(nxt);
}
if (depth[node] > H) {
H = depth[node];
}
}
void build(int node) {
if (depth[node] % root == 1) {
an[node] = dad[node];
}
else {
an[node] = an[dad[node]];
}
for (int nxt : v[node]) {
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;
}