Pagini recente » Cod sursa (job #2840726) | Cod sursa (job #2868507) | Cod sursa (job #484022) | Cod sursa (job #2048584) | Cod sursa (job #2196930)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int N=100005;
int n,tin[N],tout[N],t[21][N],q,timp;
bool viz[N];
vector <int> a[N];
void citire()
{
in>>n>>q;
for(int i=2; i<=n; i++)
{
in>>t[0][i];
a[t[0][i]].push_back(i);
}
}
void precalculare()
{
for(int i=1; 1<<i <= n; i++)
{
for(int j=1; j<=n; j++)
{
t[i][j]=t[i-1][t[i-1][j]];
}
}
}
void dfs(int nod)
{
int i,vecin;
tin[nod]=++timp;
viz[nod]=1;
for(i=0; i<a[nod].size(); i++)
{
vecin=a[nod][i];
if(!viz[vecin])
{
dfs(vecin);
}
}
tout[nod]= ++timp;
}
bool stramos(int nod1,int nod2)
{
if(nod1==nod2)
return true;
if(tin[nod1]<tin[nod2] && tout[nod1]>tout[nod2])
return true;
return false;
}
/*
t[i][j] = t[i-1][t[i-1][j]]
t[i][j] = al 2^i lea stramos al lui j
lpas=L
while(lpas!=0)
{
if(lpas <=L && t[lpas][x]<= && !stramos(t[lpas][x],y]))
x=t[lpas][x];
lpas--;
}
return t[x][0];
*/
void lca(int x,int y)
{
if(stramos(x,y)==1)
{
out<<x<<'\n';
return;
}
if(stramos(y,x)==1)
{
out<<y<<'\n';
return;
}
int lpas;
lpas=20;
while(lpas>=0)
{
//out<<lpas<<" "<<stramos(t[lpas][x],y)<<" ";
if(t[lpas][x] != 0 && !stramos(t[lpas][x],y))
{
x=t[lpas][x];
//out<<x<<endl;
}
lpas--;
}
//return t[0][x];
out<<t[0][x]<<'\n';
}
void raspuns()
{
while(q--)
{
int x,y;
in>>x>>y;
//out<<lca(x,y)<<'\n';
lca(x,y);
}
}
int main()
{
int i,j;
citire();
precalculare();
dfs(1);
raspuns();
/*
out<<endl;
for(i=1; i<=n; i++)
out<<tin[i]<<" ";
out<<endl;
for(i=1; i<=n; i++)
out<<tout[i]<<" ";
out<<endl;
*/
/* for(i=0; 1<<i <=n ; i++)
{
for(j=1; j<=n; j++)
out<<t[i][j]<<" ";
out<<endl;
}
*/
return 0;
}