Cod sursa(job #3237947)

Utilizator eZ_tAtDarius Tat eZ_tAt Data 14 iulie 2024 15:34:09
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>

using namespace std;

ifstream fin("cautbinar.in");
ofstream fout("cautbinar.out");
int n;
int a[100001];


inline 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;
    }
}


inline 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() {
    fin >> n;
    for(int i = 0; i < n; i++) {
        fin >> a[i];
    }
    int q;
    fin >> q;
    int x;
    short cerr;
    while(q--) {
        fin >> cerr >> x;
        if(cerr == 0 || cerr == 1) {
            fout << cb0(x) << '\n';
        } else {
            fout << cb2(x) << '\n';
        }
    }
    return 0;
}