Pagini recente » Cod sursa (job #1024163) | Cod sursa (job #3264177) | Cod sursa (job #3210923) | Cod sursa (job #2962311) | Cod sursa (job #3155017)
#include <bits/stdc++.h>
using namespace std;
/// INPUT / OUTPUT
const string problem = "lca";
ifstream fin(problem + ".in");
ofstream fout(problem + ".out");
/// GLOBAL VARIABLES
const int NMAX = 1e5 + 5, LOG = 25;
int n, m, k;
int g[NMAX], depth[2*NMAX], euler[2*NMAX], poz[2*NMAX];
int rmq[LOG][2 * NMAX];
vector<int>graph[NMAX];
inline void DFS(int curr_node, int h)
{
euler[++k] = curr_node;
depth[k] = h;
poz[curr_node] = k;
for(auto new_node : graph[curr_node])
{
DFS(new_node, h + 1);
euler[++k] = curr_node;
depth[k] = h;
}
}
inline void RMQ()
{
for(int i = 1; i <= k; ++ i)
rmq[0][i] = i;
for(int i = 1; (1 << i) <= k; ++ i)
{
for(int j = 1; j <= k; ++ j)
{
if(depth[rmq[i-1][j]] < depth[rmq[i-1][j + (1 << (i - 1))]])
rmq[i][j] = rmq[i-1][j];
else
rmq[i][j] = rmq[i-1][j + (1 << (i - 1))];
}
}
}
int main()
{
ios::sync_with_stdio(false);
fin.tie(NULL);
fout.tie(NULL);
fin >> n >> m;
for(int i = 2; i <= n; ++ i)
{
fin >> g[i];
graph[g[i]].push_back(i);
}
DFS(1, 0);
RMQ();
while(m--)
{
int a, b;
fin >> a >> b;
a = poz[a];
b = poz[b];
if(a > b)
swap(a, b);
int k = log2(b - a + 1);
if(depth[rmq[k][a]] < depth[rmq[k][b - (1 << k) + 1]])
fout << euler[rmq[k][a]] << '\n';
else
fout << euler[rmq[k][b - (1 << k) + 1]] << '\n';
}
}