Cod sursa(job #2703539)

Utilizator vnedelcuVictor Andrei Nedelcu vnedelcu Data 8 februarie 2021 18:48:23
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <stdio.h>

using namespace std;

const int N_MAX = 100000;

int arr[N_MAX];
int n, m;

// 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() {
    FILE * fin, * fout;

    fin = fopen("cautbin.in", "r");
    fscanf(fin, "%d", &n);
    for (int i = 0; i < n; i++) {
        fscanf(fin, "%d", &arr[i]);
    }

    fout = fopen("cautbin.out", "w");
    int op, val, index;

    fscanf(fin, "%d", &m);
    for (int i = 0; i < m; i++) {
        fscanf(fin, "%d%d", &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++;
        }

        fprintf(fout, "%d\n", index);
    }

    fclose(fin);
    fclose(fout);

    return 0;
}