Cod sursa(job #1044946)

Utilizator mucenic_b101Bogdan Mucenic mucenic_b101 Data 30 noiembrie 2013 17:33:40
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <cstdio>

int v[100001], n;

inline int bsearch( int x ) {

    int poz = 0, avans = 1 <<20;
    while( avans ) {
        if( poz + avans < n && v[poz + avans] <= x )
            poz += avans;
        avans >>= 1;
    }
    return poz;
}

int main () {

    FILE *f, *g;
    f = fopen( "cautbin.in", "r" );
    g = fopen( "cautbin.out", "w" );

    int a, x, poz, m;

    fscanf( f, "%d", &n );

    for( int i = 0 ; i < n ; ++i )
        fscanf( f, "%d", &v[i] );

    fscanf( f, "%d", &m );

    for( int i = 0 ; i < m ; ++i ) {
        fscanf( f, "%d%d", &a, &x );
        poz = bsearch( x );
        if( a == 2 ) {
            while( poz >=0 && v[poz] >= x )
                --poz;
            ++poz;
        }

        if( a == 0 && v[poz] != x )
            fprintf( g, "-1\n" );
        else fprintf( g, "%d\n", poz + 1 );
    }

    fclose( f );
    fclose( g );

    return 0;

}