Pagini recente » Cod sursa (job #3360333) | Cod sursa (job #3360343) | Cod sursa (job #3360377) | Cod sursa (job #3360336) | Cod sursa (job #3360349)
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
using namespace std;
const int N=1e5+5,M=18;
int n,m,pc;
int t[N];
int p_start[N],p_end[N];
int stramos[N][M];
bitset<N> viz;
vector<int> g[N];
bool este_stramos(int x,int y)
{
return p_start[x]<=p_start[y] and p_end[y]<=p_end[x];
}
void dfs(int nod)
{
viz[nod]=1;
p_start[nod]=pc++;
for(auto el:g[nod])
if(!viz[el])
dfs(el);
p_end[nod]=pc++;
}
int lca(int a, int b)
{
if(este_stramos(a,b))return a;
if(este_stramos(b,a))return b;
for(int p=M-1; p>=0; p--)
{
int c=stramos[a][p];
if(c and !este_stramos(c,b))
{
a=c;
}
}
return stramos[a][0];
}
void generare_stramosi()
{
int i(1);
for(; i<=n; i++)stramos[i][0]=t[i];
for(int p(1); p<M; p++)
{
for(int nod=1; nod<=n; nod++)
stramos[nod][p]=
stramos[stramos[nod][p-1]][p-1];
}
}
int main()
{
ifstream fin("lca.in");
fin>>n>>m;
int i(2),j;
for(; i<=n; i++)
{
fin>>t[i];
g[t[i]].push_back(i);
}
dfs(1);
generare_stramosi();
ofstream fout("lca.out");
while(m--)
{
fin>>i>>j;
fout<<lca(i,j)<<'\n';
}
fin.close();
fout.close();
return 0;
}