Pagini recente » Cod sursa (job #2958200) | Cod sursa (job #749253) | Cod sursa (job #718114) | Cod sursa (job #725610) | Cod sursa (job #2360729)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin ("lca.in" );
ofstream fout ("lca.out");
const int N = 100001, L = 21;
int log[L], r[L][2*N], e[2*N], ne, nivel[N], poz[N];
vector <int> fii[N];
void dfs ( int x )
{
e[++ne] = x;
poz[x] = ne;
for ( auto y : fii[x])
{
nivel[y] = 1 + nivel[x];
dfs(y);
e[++ne] = x;
}
}
int main()
{
int n, m;
fin >> n >> m;
for ( int i = 2; i <= n; i++ )
{
int x;
fin >> x;
fii[x].push_back (i);
}
dfs (1);
for ( int i = 2; i <= ne; i++ )
{
log[i] = log[i/2] + 1;
}
for ( int j = 1; j <= ne; j ++ )
{
r[0][j] = e[j];
}
for ( int i = 1; i <= log[ne]; i++ )
{
for ( int j = 1 << i; j <= ne; j++ )
{
int st, dr;
st = r[i-1][j - ( 1 << ( i-1 ) )];
dr = r[i-1][j];
if ( nivel [st] <= nivel[dr] )
{
r[i][j] = st;
}
else
{
r[i][j] = dr;
}
}
}
while ( m != 0 )
{
int x, y;
m--;
fin >> x >> y;
if ( poz[x] > poz[y] )
{
x += y;
y = x - y;
x = x - y;
}
int lung = poz[y] - poz[x] + 1;
int l = log[lung];
if ( nivel[r[l][poz[y]]] < nivel [r[l][poz[x] + (1 << l )]])
fout << r[l][poz[y]] << "\n";
else
fout << r[l][poz[x] + (1 <<l)] << "\n";
}
return 0;
}