Pagini recente » Cod sursa (job #2495027) | Cod sursa (job #1871766) | Cod sursa (job #2904841) | Cod sursa (job #1240693) | Cod sursa (job #3004071)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define FOR(WHATEVER) for(int i = 1; i <= WHATEVER; ++ i)
/// INPUT / OUTPUT
const string problem = "lca";
ifstream fin(problem + ".in");
ofstream fout(problem + ".out");
/// GLOBAL VARIABLES
const ll NMAX = 1e5, LOG = 25, MOD = 1e9 + 7, INF = 1e9;
/// SOLUTION
int n, q, k;
int lin[2*NMAX], depth[2*NMAX], poz[2*NMAX];
int rmq[LOG][2 * NMAX];
vector<int>g[NMAX];
inline void dfs(int x, int h)
{
lin[++k] = x;
depth[k] = h;
poz[x] = k;
for(auto new_node : g[x])
{
dfs(new_node, h + 1);
lin[++k] = x;
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))];
}
}
}
/// READING THE INPUT
int main()
{
ios::sync_with_stdio(false);
fin.tie(NULL);
fout.tie(NULL);
fin >> n >> q;
for(int i = 2; i <= n; ++ i)
{
int a;
fin >> a;
g[a].push_back(i);
}
dfs(1, 0);
RMQ();
while(q--)
{
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]])
cout << lin[rmq[k][a]] << '\n';
else
cout << lin[rmq[k][b - (1 << k) + 1]] << '\n';
}
}