Pagini recente » Cod sursa (job #299402) | Cod sursa (job #2051897) | Cod sursa (job #3031456) | Cod sursa (job #1821378) | Cod sursa (job #2354320)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin( "lca.in" );
ofstream fout( "lca.out" );
const int NMAX = 100005;
const int KMAX = 22;
int N, nr_q;
vector <int> Ad[NMAX];
int pos[NMAX];
int euler[2 * NMAX];
int lvl[2 * 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;
lvl[last] = depth;
if( pos[nod] == 0 ) pos[nod] = last;
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[ pos[ mat[i - 1][j] ]] > lvl[ pos[ mat[i - 1][aux] ] ] )
mat[i][j] = mat[i - 1][aux];
}
int x, y;
int logg, ans;
for( int i = 1; i <= nr_q; ++i )
{
fin >> x >> y;
x = pos[x]; y = pos[y];
logg = lg[y - x + 1];
aux = y - ( 1 << logg ) + 1;
ans = mat[logg][x];
if( lvl[ pos[ans] ] > lvl[ pos[ mat[logg][aux] ] ] )
ans = mat[logg][aux];
fout << ans << '\n';
}
}
int main()
{
Read();
Do();
return 0;
}