Cod sursa(job #2714513)

Utilizator TigoanMateiTigoan Matei-Daniel TigoanMatei Data 1 martie 2021 21:29:16
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#include <climits>

using namespace std;

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

int n, m, V, x, pos;
int v[100005];

int main()
{
    in >> n;
    for(int i = 1; i <= n; ++ i)
        in >> v[i];
    in >> m;
    for(int i = 1; i <= m; ++ i)
    {
        in >> V >> x;

        pos = 0;

        if(!V)
        {
            for(int j = (1 << 30); j > 0; j /= 2)
                if(pos + j <= n && v[pos + j] <= x)
                    pos += j;

            if(v[pos] == x) out << pos << '\n';
            else out << -1 << '\n';
        }
        else if(V == 1)
        {
            for(int j = (1 << 30); j > 0; j /= 2)
                if(pos + j <= n && v[pos + j] <= x)
                    pos += j;

            out << pos << '\n';
        }
        else
        {
            for(int j = (1 << 30); j > 0; j /= 2)
                if(pos + j <= n && v[pos + j] < x)
                    pos += j;

            out << pos + 1 << '\n';
        }
    }
    return 0;
}