Pagini recente » Cod sursa (job #1830470) | Cod sursa (job #2401307)
#include <fstream>
using namespace std;
ifstream fin( "stramosi.in" );
ofstream fout( "stramosi.out" );
const int NMAX = 250005;
int N, T;
int mat[NMAX][20];
int pre[NMAX];
void Read()
{
fin >> N >> T;
for( int i = 1; i <= N; ++i )
fin >> mat[i][0];
}
int BiggestPow( int val )
{
if( val == 0 ) return -1;
int ans = 0;
while( true )
{
int aux = 1 << ( ans + 1 );
if( aux > val ) return ans;
else ++ans;
}
}
void Do()
{
int aux, auxp;
aux = 0;
auxp = 1;
for( int i = 2; i <= N; ++i )
{
if( i == auxp * 2 )
{
++aux;
auxp *= 2;
}
pre[i] = aux;
}
for( int j = 1; j <= 19; ++j )
for( int i = 1; i <= N; ++i )
{
aux = mat[i][j - 1];
if( aux > 0 ) mat[i][j] = mat[aux][j - 1];
}
int nod, D;
for( int i = 1; i <= T; ++i )
{
fin >> nod >> D;
aux = pre[D];
while( D > 0 )
{
nod = mat[nod][aux];
D -= ( 1 << aux );
aux = pre[D];
}
fout << nod << '\n';
}
}
int main()
{
Read();
Do();
return 0;
}