Cod sursa(job #3237940)

Utilizator eZ_tAtDarius Tat eZ_tAt Data 14 iulie 2024 15:27:26
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream cin("cautbinar.in");
ofstream cout("cautbinar.out");
int n;
int a[n];


int cb0(int x) {
    int st = 0; 
    int dr = n - 1;
    int rez = -1;

    while(st <= dr) {
        int mij = (st + dr) >> 1;
        if(a[mij] <= x) {
            rez = mij;
            st = mij + 1;
        } else {
            dr = mij - 1;
        }
    }
    if (rez == -1 || a[rez] != x) {
        return -1;
    } else {
        return rez + 1;
    }
}

int cb1(int x) {
    return cb0(x);  // cb0 and cb1 are identical
}

int cb2(int x) {
    int st = 0; 
    int dr = n - 1;
    int rez = -1;
    
    while(st <= dr) {
        int mij = (st + dr) >> 1;
        if(a[mij] >= x) {
            rez = mij;
            dr = mij - 1;
        } else {
            st = mij + 1;
        }
    }
    if (rez == -1 || a[rez] != x) {
        return -1;
    } else {
        return rez + 1;
    }
}

int main() {
    cin >> n;
    for(int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int q;
    cin >> q;
    int x;
    short cerr;
    while(q--) {
        cin >> cerr >> x;
        if(cerr == 0) {
            cout << cb0(x) << '\n';
        } else if(cerr == 1) {
            cout << cb1(x) << '\n';
        } else {
            cout << cb2(x) << '\n';
        }
    }
    return 0;
}