Cod sursa(job #3265940)

Utilizator ShokapKaplonyi Akos Shokap Data 4 ianuarie 2025 12:49:11
Problema Cautare binara Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <iostream>
#include <fstream>

using namespace std;

int searchUpper(int n, unsigned int t[], unsigned int x) {
    
    int bal = 0, jobb = n-1;

    while (bal < jobb) {
        int kozep = (bal+jobb)/2;

        if (t[kozep] <= x)
            bal = kozep+1;
        else
            jobb = kozep;
    }

    
    if (t[jobb-1] == x) return jobb;
    else return -1;
}
int searchUpperMod(int n, unsigned int t[], unsigned int x){

    int bal = 0, jobb = n;

    while (bal < jobb) {
        int kozep = (bal+jobb)/2;

        if (t[kozep] <= x)
            bal = kozep+1;
        else
            jobb = kozep;
    }

    return jobb;
}
int searchLower(int n, unsigned int t[], unsigned int x){
    int bal = 0, jobb = n;

    while (bal < jobb) {
        int kozep = (bal+jobb)/2;

        if (t[kozep] < x)
            bal = kozep+1;
        else 
            jobb = kozep;
    }

    return bal+1;

}


int main () {
    ifstream input ("cautbin.in");
    ofstream output ("cautbin.out");

    int n;
    input >> n;

    unsigned int arr[n];
    for (int i = 0; i < n; i++){
        input >> arr[i];
    }

    int m;
    input >> m;

    for (int i = 1; i <= m; i++){
        unsigned int type, x;
        input >> type >> x;

        switch (type){
            case 0:
                output << searchUpper(n, arr, x) << '\n';
                break;
            case 1:
                output << searchUpperMod(n, arr, x) << '\n';
                break;
            case 2:
                output << searchLower(n, arr, x) << '\n';
                break;
        }
    }

    return 0;
}