Cod sursa(job #2334584)

Utilizator darksky185Alexandru Gabriel darksky185 Data 2 februarie 2019 18:30:08
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int v[100005];

int c1( int n )
{
    int pos = 0;
    for( int m = 1 << 20; m > 0; m /= 2 )
        if( pos + m <= v[0] && v[pos + m] <= n )
            pos += m;
    return pos;
}

int c3( int n )
{
    int pos = 0;
    for( int m = 1<<20; m > 0; m /= 2 )
       if( pos + m <= v[0] && v[pos + m] <= n )
            pos += m;
    while( v[pos] == n )
        pos--;
    pos++;
    return pos;
}

int main()
{
    int n, i, m, x, q, pos;
    fin >> n;
    v[0] = n;
    for( i = 1; i <= n; ++i )
        fin >> v[i];
    fin >> q;
    for( i = 1; i <= q; ++i )
    {
        fin >> x >> m;
        pos = c1(m);
        if( x == 0 )
            {
                if( v[pos] != m )
                    fout << -1 << '\n';
                else
                    fout << pos << '\n';
            }
        else
            if( x == 1 )
                fout << pos << '\n';
            else
                fout << c3(m) << '\n';
    }

    return 0;
}