Cod sursa(job #2703535)

Utilizator vnedelcuVictor Andrei Nedelcu vnedelcu Data 8 februarie 2021 18:42:26
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <vector>

using namespace std;

const int N_MAX = 100000;
int n;
int arr[N_MAX];

// returns the first index of a number >= val
int lower_bound(int val) {
    int bit = 1;
    for (; bit < n; bit <<= 1);

    int index = n - 1;
    for (; bit; bit >>= 1) {
        if (index - bit >= 0 && arr[index - bit] >= val) {
            index -= bit;
        }
    }

    if (arr[index] < val) {
        index = -1;
    }

    return index;
}

// returns the last index of a number <= val
int upper_bound(int val) {
    int bit = 1;
    for (; bit < n; bit <<= 1);

    int index = 0;
    for (; bit; bit >>= 1) {
        if (index + bit < n && arr[index + bit] <= val) {
            index += bit;
        }
    }

    if (arr[index] > val) {
        index = -1;
    }

    return index;
}

int main() {
    ifstream fin("cautbin.in");
    ofstream fout("cautbin.out");

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

    int m;
    fin >> m;

    int op, val, index;
    for (int i = 0; i < m; i++) {
        fin >> op >> val;

        if (op < 2) {
            index = upper_bound(val);
            if (op == 0 && arr[index] != val) {
                index = -1;
            }
        } else {
            index = lower_bound(val);
        }

        if (index != - 1) {
            index++;
        }

        fout << index << endl;
    }

    fin.close();
    fout.close();

    return 0;
}