Cod sursa(job #2509843)

Utilizator Tudor06MusatTudor Tudor06 Data 14 decembrie 2019 23:38:54
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <stdio.h>
#include <ctype.h>

using namespace std;

const int NMAX = 1e5;

int v[NMAX];

FILE *fin, *fout;

int numar() {
    int nr = 0;
    char ch;
    while ( isspace( ch = fgetc( fin ) ) );
    nr = ch - '0';
    while ( isdigit( ch = fgetc( fin ) ) )
        nr = nr * 10 + ch - '0';
    return nr;
}

int cbmin( int st, int dr, int x ) {
    while ( st < dr - 1 ) {
        int mij = ( st + dr ) / 2;
        if ( v[mij] > x ) {
            dr = mij;
        } else
            st = mij;
    }
    return st;
}

int cbmax( int st, int dr, int x ) {
    while ( st < dr - 1 ) {
        int mij = ( st + dr ) / 2;
        ///printf( "%d %d %d\n", st, mij, dr );
        if ( v[mij] < x ) {
            st = mij;
        } else {
            dr = mij;
        }
    }
    if ( v[st] >= x )
        return st;
    return dr;
}

int main() {
    fin = fopen( "cautbin.in", "r" );
    fout = fopen( "cautbin.out", "w" );
    int n, i, m;
    n = numar();
    for ( i = 0; i < n; i ++ )
        v[i] = numar();
    m = numar();
    for ( i = 0; i < m; i ++ ) {
        int cer, x, poz;
        cer = numar();
        x = numar();
        if ( cer < 2 ) {
            poz = cbmin( 0, n, x );
            if ( cer == 0 && v[poz] == x )
                fprintf( fout, "%d\n", poz + 1 );
            else if ( cer == 0 )
                fprintf( fout, "-1\n" );
            else {
                fprintf( fout, "%d\n", poz + 1 );
            }
        } else {
            poz = cbmax( 0, n, x );
            fprintf( fout, "%d\n", poz + 1 );
        }
    }
    fclose( fin );
    fclose( fout );
    return 0;
}