Cod sursa(job #1522340)

Utilizator zacuscaAlex Iordache zacusca Data 11 noiembrie 2015 16:34:11
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>

using namespace std;

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

int n, V[100003], m;

int main()
{
    in >> n;

    for (int i = 1; i <= n; i++) in >> V[i];

    int log = 1;

    for (; log <= n; log <<= 1);

    in >> m;

    for (int t, x, poz, step; m; --m)
    {
        in >> t >> x;

        if(t < 2)
        {
            for (step = log, poz = 0; step; step >>= 1)
                if (poz + step <= n and V[poz + step] <= x)
                poz += step;

            if(t == 0 and V[poz] != x) out << "-1\n";

            else out << poz << '\n';
        }

        else
        {
            for (step = log, poz = n; step; step >>= 1)
            if (poz - step > 0 and V[poz - step] >= x)
            poz -= step;

            out << poz << '\n';
        }
    }
    out.close();
    return 0;
}