Cod sursa(job #2654664)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 1 octombrie 2020 20:44:50
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define lsb(x) x & -x

using namespace std;

int binarySearch(const vector<int> &v, int n, int value) {
    int left = 1, right = n;
    while(left < right) {
        int mid = (left + right) / 2;
        if(value < v[mid]) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }

    assert(left == right);
    int ans = left;
    if(v[ans] > value)
        ans --;
    return ans;
}

int main() {
    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int n;
    cin >> n;
    vector<int> v(n + 1, 0);
    for(int i = 1; i <= n; i ++)
        cin >> v[i];

    int m;
    cin >> m;
    while(m --) {
        int type, x;
        cin >> type >> x;
        if(type == 0) {
            int sol = binarySearch(v, n, x);
            if (sol > 0 && v[sol] == x)
                cout << sol << "\n";
            else
                cout << "-1\n";
        }
        if(type == 1) {
            cout << binarySearch(v, n, x) << "\n";
        }
        if(type == 2) {
            cout << 1 + binarySearch(v, n, x - 1) << "\n";
        }
    }

    return 0;
}