Cod sursa(job #2338473)

Utilizator Cristian25Cristian Stanciu Cristian25 Data 7 februarie 2019 15:30:05
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
#define date "cautbin.in"
#define rezultate "cautbin.out"
#define len 100000

using namespace std;

ifstream in(date);
ofstream out(rezultate);

int N, M, v[len];

int binary_search(int val)
{
    int step, i;
    for(step = 1; step < N; step <<= 1);
    for(i = 0; step; step >>= 1)
        if(i + step < N && v[i + step] <= val)
            i += step;
    return i + 1;
}

int binary_search1(int val)
{
    int step, i;
    for(step = 1; step < N; step <<= 1);
    for(i = N - 1; step; step >>= 1)
        if(i - step >= 0 && v[i - step] >= val)
            i -= step;
    return i + 1;
}

int main()
{
    in >> N;
    for(int i = 0; i < N;)
        in >> v[i++];
    in >> M;
    for(int i = 1; i <= M; ++i)
    {
        int task, x;
        in >> task >> x;
        if(!task)
        {
            int k = binary_search(x);
            out << (v[k - 1] == x ? k : -1);
        }
        else if(task == 1)
            out << binary_search(x);
        else
            out << binary_search1(x);
        out << '\n';
    }
    return 0;
}