Pagini recente » Cod sursa (job #1784204) | Cod sursa (job #506693) | Cod sursa (job #899709) | Cod sursa (job #2615982) | Cod sursa (job #2354661)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin( "lca.in" );
ofstream fout( "lca.out" );
const int NMAX = 500005;
const int KMAX = 22;
int N, nr_q;
vector <int> Ad[NMAX];
int pos[NMAX];
int euler[2 * NMAX];
int lvl[NMAX];
int last;
int lg[2 * NMAX];
int mat[KMAX][NMAX];
void Read()
{
fin >> N >> nr_q;
int x;
for( int i = 2; i <= N; ++i )
{
fin >> x;
Ad[x].push_back( i );
}
}
void DFS( int nod, int depth )
{
euler[++last] = nod;
if( pos[nod] == 0 )
{
pos[nod] = last;
lvl[nod] = depth;
}
for( int i = 0; i < Ad[nod].size(); ++i )
{
DFS( Ad[nod][i], depth + 1 );
euler[++last] = nod;
//lvl[last] = nod;
}
}
void Do()
{
DFS( 1, 1 );
for( int i = 2; i <= last; ++i )
lg[i] = lg[i / 2] + 1;
for( int i = 1; i <= last; ++i )
mat[0][i] = euler[i];
int aux;
for( int i = 1; ( 1 << i ) <= last; ++i )
for( int j = 1; j + ( 1 << i ) - 1 <= last; ++j )
{
mat[i][j] = mat[i - 1][j];
aux = j + ( 1 << ( i - 1 ) );
if( lvl[ mat[i - 1][j] ] > lvl[ mat[i - 1][aux] ] )
mat[i][j] = mat[i - 1][aux];
}
/*
for( int i = 0; ( 1 << i ) < last; ++i )
{
for( int j = 1; j <= last; ++j )
fout << mat[i][j] << ' ';
{1}
fout << '\n';
}*/
int x, y;
int logg, ans;
for( int i = 1; i <= nr_q; ++i )
{
fin >> x >> y;
x = pos[x]; y = pos[y];
if( x > y ) swap( x, y );
logg = lg[y - x + 1];
aux = y - ( 1 << logg ) + 1;
ans = mat[logg][x];
//fout << ans << ' ' << mat[logg][aux] << '\n';
if( lvl[ans] > lvl[ mat[logg][aux] ] )
ans = mat[logg][aux];
fout << ans << '\n';
}
}
int main()
{
Read();
Do();
return 0;
}