Pagini recente » Cod sursa (job #2482287) | Cod sursa (job #1035754) | Monitorul de evaluare | Cod sursa (job #102844) | Cod sursa (job #3271331)
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int n, m, i, j, t[100005], depth[100005], p, k, x, y, lg, pow2, poz[100005], st, dr;
bool viz[100005];
vector <int> v[100005];
vector <pair<int, int>> eulertour;
struct rangemin
{
int nod, depth;
}rmq[21][200005];
void dfs(int nod)
{
viz[nod]=1;
eulertour.push_back({nod, depth[nod]});
poz[nod]=eulertour.size();
for(auto i: v[nod])
if(viz[i]==0)
{
depth[i]=depth[nod]+1;
dfs(i);
eulertour.push_back({nod, depth[nod]});
}
}
int main()
{
fin>>n>>m;
for(i=2; i<=n; i++)
{
fin>>t[i];
v[t[i]].push_back(i);
}
dfs(1);
int nr=0;
for(auto i: eulertour)
{
nr++;
rmq[0][nr].nod=i.first;
rmq[0][nr].depth=i.second;
}
p=2;
while(p<=nr)
{
k++;
for(i=1; i<=nr-p+1; i++)
if(rmq[k-1][i].depth<rmq[k-1][i+p/2].depth)
{
rmq[k][i].depth=rmq[k-1][i].depth;
rmq[k][i].nod=rmq[k-1][i].nod;
}
else
{
rmq[k][i].depth=rmq[k-1][i+p/2].depth;
rmq[k][i].nod=rmq[k-1][i+p/2].nod;
}
p*=2;
}
while(m--)
{
fin>>x>>y;
st=min(poz[x], poz[y]);
dr=max(poz[x], poz[y]);
lg=dr-st+1;
p=log2(lg);
pow2=(1<<p);
if(rmq[p][st].depth<rmq[p][dr-pow2+1].depth)
fout<<rmq[p][st].nod<<'\n';
else
fout<<rmq[p][dr-pow2+1].nod<<'\n';
}
return 0;
}