Pagini recente » Cod sursa (job #2684540) | Cod sursa (job #1536476) | Cod sursa (job #329040) | Autentificare | Cod sursa (job #2672743)
/**
infoarena.ro/problema/lca
Lowest Common Ancestor
*/
#include <fstream>
#include <cstdio>
#include <vector>
using namespace std;
ofstream fout("lca.out");
const int nmax=100020;
const int Size=8200;
int n,m;
vector <int> g[nmax];
int a[20][nmax],log2[nmax];
int use[nmax],vt[nmax],nivel[nmax];
char Buffer[Size];
int Pos;
inline void ReadValue(int & Value)
{
Value=0;
while(Buffer[Pos]<'0' || Buffer[Pos]>'9')
{
Pos++;
if(Pos == Size)
{
fread(Buffer, 1, Size, stdin);
Pos=0;
}
}
while(Buffer[Pos]>='0' && Buffer[Pos]<='9')
{
Value = Value*10 + Buffer[Pos] - '0';
Pos++;
if(Pos == Size)
{
fread(Buffer, 1, Size, stdin);
Pos=0;
}
}
}
void citire()
{
freopen("lca.in","r",stdin);
ReadValue(n);
ReadValue(m);
for(int i=2;i<=n;i++)
{
ReadValue(vt[i]);
g[vt[i]].push_back(i);
}
}
void precalcul()
{
for(int i=2;i<=n;i++)
log2[i]=log2[i/2]+1;
for(int i=1;i<=n;i++)
a[0][i]=vt[i];
for(int i=1;(1<<i)<=n;i++)
for(int j=1;j<=n;j++)
a[i][j]=a[i-1][a[i-1][j]];
}
void dfs(int nod)
{
use[nod]=1;
for(int i=0;i<(int)g[nod].size();i++)
{
int vecin = g[nod][i];
if(!use[vecin])
{
nivel[vecin]=nivel[nod]+1;
dfs(vecin);
}
}
}
int ancestor(int x, int y)
{
if(nivel[x]<nivel[y])
swap(x,y);
while(nivel[x]!=nivel[y])
{
int k=log2[nivel[y]-nivel[x]];
x=a[k][x];
}
if(x==y)
{
return x;
}
for(int k=log2[nivel[x]]; k>=0; k--)
{
if(a[k][x]!=a[k][y])
{
x=a[k][x];
y=a[k][y];
}
}
return vt[x];
}
void rezolv()
{
dfs(1);
while(m--)
{
int x,y;
ReadValue(x);
ReadValue(y);
fout<<ancestor(x,y)<<endl;
}
}
int main()
{
citire();
precalcul();
rezolv();
return 0;
}