Cod sursa(job #1253037)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 31 octombrie 2014 18:49:28
Problema Stramosi Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.74 kb
#include<fstream>

using namespace std;

ifstream fin( "stramosi.in" );
ofstream fout( "stramosi.out" );

const int amax = 18;
const int nmax = 250000;
int d[ nmax + 1 ][ amax ];

int main() {
    int n, q, x, y, k;
    fin >> n >> q;
    for( int i = 1; i <= n; ++ i ) {
        fin >> d[ i ][ 0 ];
    }
    for( int j = 1; j < amax; ++ j ) {
        for( int i = 1; i <= n; ++ i ) {
            d[ i ][ j ] = d[ d[ i ][j - 1] ][ j - 1 ];
        }
    }
    while ( q -- ) {
        fin >> x >> y;
        k = 0;
        while ( y > 0 ) {
            if ( y % 2 == 1 ) {
                x = d[ x ][ k ];
            }
            ++ k;
            y /= 2;
        }
        fout << x << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}