Pagini recente » Cod sursa (job #2949203) | Cod sursa (job #1916785) | Cod sursa (job #2300557) | Cod sursa (job #724773) | Cod sursa (job #2402460)
#include <fstream>
#include <string>
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];
int ParseIn()
{
string S;
fin >> S;
int nr = 0;
for( int i = 0; i < S.size(); ++i )
nr = nr * 10 + S[i] - '0';
return nr;
}
void Read()
{
fin >> N >> T;
for( int i = 1; i <= N; ++i )
{
int nr = ParseIn();
mat[i][0] = nr;
}
}
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];
if( pre[D] > pre[D - 1] )
{
fout << mat[nod][pre[D]] << '\n';
continue;
}
while( D > 0 )
{
nod = mat[nod][aux];
D -= ( 1 << aux );
aux = pre[D];
}
fout << nod << '\n';
}
}
int main()
{
Read();
Do();
return 0;
}