Cod sursa(job #2877833)

Utilizator mihai_sabouSabou Mihai mihai_sabou Data 25 martie 2022 14:04:55
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <bits/stdc++.h>

using namespace std;

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

    int n;
    in >> n;

    int v[n + 1];

    for (int i{}; i < n; ++i) {
        in >> v[i];
    }

    int m;
    in >> m;

    for (int i{}; i < m; ++i) {
        int c, x;
        in >> c >> x;
        int y;
        if (c == 0) {
            y = upper_bound(v, v + n, x) - v - 1;
            if (y <= n && y >= 1 && v[y] == x) {
                out << y + 1 << '\n';
            }
            else {
                out << '-1\n';
            }
            continue;
        }
        if (c == 1) {
            y = lower_bound(v, v + n, x + 1) - v;
            out << y << '\n';
            continue;
        }
        y = upper_bound(v, v + n, x - 1) - v + 1;
        out << y << '\n';
    }
}