Cod sursa(job #1371414)

Utilizator Mr.DoomRaul Ignatus Mr.Doom Data 3 martie 2015 21:21:21
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
using namespace std;

ifstream is("cautbin.in");
ofstream os("cautbin.out");

int n, m;
int a[100001];
int type, value, position;
long long logn = 1;
int byte;

int binarySLowest(int val);
int binarySHighest(int val);

int main()
{
    is >> n;
    for ( int i = 1; i <= n; ++i )
        is >> a[i];

    for ( logn; logn < n; logn <<= 1 );
    is >> m;
    for ( int i = 1; i <= m; ++i )
    {
        is >> type >> value;
        if ( type < 2 )
        {
            position = binarySLowest(value);
            if ( !type && a[position] != value )
                os << "-1\n";
            else
                os << position << '\n';
        }
        else
            os << binarySHighest(value) << '\n';
    }
    is.close();
    os.close();
    return 0;
}

int binarySLowest(int val)
{
    int pos;
    byte = logn;
    for ( pos = 0; byte; byte >>= 1 )
        if ( pos + byte <= n && a[pos + byte] <= val )
            pos += byte;
    return pos;
}

int binarySHighest(int val)
{
    int pos;
    byte = logn;
    for ( pos = n; byte; byte >>= 1 )
        if ( pos - byte > 0 && a[pos - byte] >= val )
            pos -= byte;
    return pos;
}