Pagini recente » Cod sursa (job #2271034) | Cod sursa (job #593139) | Istoria paginii utilizator/nenciugeorgel8b | Cod sursa (job #991629) | Cod sursa (job #2445771)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int NMAX = 1e5;
const int LGMAX = 18;
int N, M;
int heights[NMAX + 5], firstApEuler[NMAX + 5];
vector <int> sons[NMAX + 5];
vector <int> rmq[LGMAX + 5];
void DFS(int node, int h)
{
heights[node] = h + 1;
firstApEuler[node] = rmq[0].size();
rmq[0].push_back(node);
for(auto it : sons[node]) {
DFS(it, h + 1);
rmq[0].push_back(node);
}
}
int GetLowerHeight(int x, int y)
{
if(heights[x] < heights[y])
return x;
return y;
}
void BuildRmq()
{
for(int i = 1; i <= LGMAX; i++)
{
if((1 << i) > rmq[0].size())
break;
for(int j = 0; j < rmq[0].size(); j++)
if(j + (1 << i) > rmq[0].size())
break;
else
rmq[i].push_back(GetLowerHeight(rmq[i - 1][j], rmq[i - 1][j + (1 << (i - 1))]));
}
}
int QueryRmq(int x, int y)
{
x = firstApEuler[x];
y = firstApEuler[y];
if(x > y)
swap(x, y);
int l = y - x + 1;
int k = 0;
while((1 << k) <= l)
k++;
k--;
return GetLowerHeight(rmq[k][x], rmq[k][y - (1 << k) + 1]);
}
int main()
{
int x, y;
fin >> N >> M;
for(int i = 2; i <= N; i++) {
fin >> x;
sons[x].push_back(i);
}
DFS(1, 0);
BuildRmq();
for(int i = 1; i <= M; i++)
{
fin >> x >> y;
fout << QueryRmq(x, y) << '\n';
}
return 0;
}