Pagini recente » Cod sursa (job #2858610) | Cod sursa (job #1605477) | Cod sursa (job #277495) | Cod sursa (job #1809645) | Cod sursa (job #3242251)
#include <bits/stdc++.h>
const std :: string FILENAME = "lca";
std :: ifstream in (FILENAME + ".in");
std :: ofstream out (FILENAME + ".out");
const int NMAX = 2e5 + 5;
const int LOGMAX = 20;
int n;
int q;
int x;
int y;
int depth[NMAX];
int first[NMAX];
int dp[LOGMAX][NMAX];
std :: vector <int> v[NMAX];
std :: vector <int> tour;
std :: bitset <NMAX> visited;
void euler(int nod)
{
tour.push_back(nod);
first[nod] = tour.size() - 1;
for(int i : v[nod])
{
if(visited[i] == false)
{
depth[i] = depth[nod] + 1;
visited[i] = true;
euler(i);
tour.push_back(nod);
}
}
}
void precalc()
{
for(int i = 0; i < tour.size(); i ++)
{
dp[0][i] = tour[i];
}
for(int i = 1; i < LOGMAX; i ++)
{
for(int j = 0; j + (1 << i) <= tour.size(); j ++)
{
if(depth[dp[i - 1][j]] < depth[dp[i - 1][j + (1 << (i - 1))]])
{
dp[i][j] = dp[i - 1][j];
}
else
{
dp[i][j] = dp[i - 1][j + (1 << (i - 1))];
}
}
}
}
int main()
{
in >> n >> q;
for(int i = 2; i <= n; i ++)
{
in >> x;
v[x].push_back(i);
}
euler(1);
precalc();
while(q --)
{
in >> x >> y;
x = first[x];
y = first[y];
if(x > y)
{
std :: swap(x, y);
}
int lg = log2(y - x + 1);
if(depth[dp[lg][x]] < depth[dp[lg][y - (1 << lg) + 1]])
{
out << dp[lg][x] << '\n';
}
else
{
out << dp[lg][y - (1 << lg) + 1] << '\n';
}
}
return 0;
}