Cod sursa(job #499383)

Utilizator SpiderManSimoiu Robert SpiderMan Data 9 noiembrie 2010 18:38:12
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.06 kb
# include <cstdio>

# define verf ++poz == hg ? fread ( ch, 1, hg, stdin ), poz = 0 : 0

const char *FIN = "stramosi.in", *FOU = "stramosi.out" ;
const int MAX = 250000, lim = 31, hg = 1 << 13 ;

int V[lim][MAX] ;
int N, M, poz ;
char ch[hg] ;

inline void cit ( int &x ) {
    if ( ch[0] == '\0' ) fread ( ch, 1, hg, stdin ) ;
    else for ( ; ch[poz] < '0' || ch[poz] > '9' ; verf ) ;
    for ( x = 0 ; ch[poz] >= '0' && ch[poz] <= '9' ; x = x * 10 + ch[poz] - '0', verf ) ;
}

int main ( void ) {
    freopen ( FIN, "r", stdin ) ;
    freopen ( FOU, "w", stdout ) ;
    cit ( N ) , cit ( M ) ;
    for ( int i = 1; i <= N; ++i ) {
        cit ( V[0][i] ) ;
    }

    for ( int i = 1; i < lim; ++i ) {
        for ( int j = 1; j <= N; ++j ) {
            V[i][j] = V[i - 1][ V[i - 1][j] ] ;
        }
    }

    for ( int a, b ; M ; --M ) {
        cit ( a ) , cit ( b ) ;
        for ( int i = 0; b ; ++i, b >>= 1 ) {
            if ( b & 1 ) {
                a = V[i][a] ;
            }
        }
        printf ( "%d\n", a ) ;
    }
}