Cod sursa(job #3237968)

Utilizator eZ_tAtDarius Tat eZ_tAt Data 14 iulie 2024 15:55:33
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
using namespace std;

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

const int N = 1e5 + 5;  // Increase array size by 5 to avoid out-of-bound issues
int a[N];
int n;

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

    while (st <= dr) {
        int mij = (st + dr) / 2;
        if (a[mij] == x) {
            rez = mij;
            st = mij + 1;  // Continue searching to the right
        } else if (a[mij] < x) {
            st = mij + 1;
        } else {
            dr = mij - 1;
        }
    }

    return rez;  // Returns -1 if not found
}

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

    while (st <= dr) {
        int mij = (st + dr) / 2;
        if (a[mij] <= x) {
            rez = mij;
            st = mij + 1;  // Continue searching to the right
        } else {
            dr = mij - 1;
        }
    }

    return rez;  // Guaranteed to find since a[1] <= x
}

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

    while (st <= dr) {
        int mij = (st + dr) / 2;
        if (a[mij] >= x) {
            rez = mij;
            dr = mij - 1;  // Continue searching to the left
        } else {
            st = mij + 1;
        }
    }

    return rez;  // Guaranteed to find since a[n] >= x
}

int main() {
    cin >> n;

    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
    }

    int q;
    cin >> q;

    while (q--) {
        short cerr;
        int x;
        cin >> cerr >> x;

        if (cerr == 0) {
            cout << cb0(x) << '\n';
        } else if (cerr == 1) {
            cout << cb1(x) << '\n';
        } else if (cerr == 2) {
            cout << cb2(x) << '\n';
        }
    }

    return 0;
}