Cod sursa(job #3261901)

Utilizator RichardChessBibire David-Alexandru RichardChess Data 7 decembrie 2024 17:54:32
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream f("cautbin.in");
ofstream g("cautbin.out");

int v[100005];

int binarySearch(int value, int n) {
    int pos = 0;

    for (int p = 20; p >= 0; --p) {
        if (pos + (1 << p) <= n and v[pos + (1 << p)] <= value) {
            pos += (1 << p);
        }
    }

    return pos;
}

int main()
{
    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);
    int n, q;
    cin >> n;

    for (int i = 1; i <= n; ++i) {
        cin >> v[i];
    }
    cin >> q;
    for (int i = 1; i <= q; ++i) {
        int type, x;
        cin >> type >> x;
        if (type == 0) {
            int pos = binarySearch(x, n);
            if (v[pos] == x) {
                cout << pos;
            } else {
                cout << -1;
            }
        } else if (type == 1) {
            int pos = binarySearch(x, n);
            cout << pos;
        } else {
            int pos = binarySearch(x - 1, n);
            cout << pos + 1;
        }
        cout << '\n';
    }
    return 0;
}