Cod sursa(job #3343174)

Utilizator MihaiDraghiciMIHAI DRAGHICI MihaiDraghici Data 26 februarie 2026 16:31:34
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
using namespace std;

int cb0(long long x, vector<long long> &v, int n) {
    int ans = -1;
    for (int pas = 1 << 17; pas > 0; pas >>= 1) {
        if (ans + pas < n && v[ans + pas] <= x) {
            ans += pas;
        }
    }
    if (ans >= 0 && v[ans] == x) return ans;
    return -1;
}

int cb1(long long x, vector<long long> &v, int n) {
    int ans = -1;
    for (int pas = 1 << 17; pas > 0; pas >>= 1) {
        if (ans + pas < n && v[ans + pas] <= x) {
            ans += pas;
        }
    }
    return ans;
}

int cb2(long long x, vector<long long> &v, int n) {
    int ans = n;
    for (int pas = 1 << 17; pas > 0; pas >>= 1) {
        if (ans - pas >= 0 && v[ans - pas] >= x) {
            ans -= pas;
        }
    }
    if (ans < n) return ans;
    return -1;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);

    int n;
    cin >> n;

    vector<long long> v(n);
    for (int i = 0; i < n; i++) {
        cin >> v[i];
    }

    int m;
    cin >> m;

    while (m--) {
        int tip;
        long long x;
        cin >> tip >> x;

        if (tip == 0) {
            int p = cb0(x, v, n);
            if (p == -1) cout << -1 << "\n";
            else cout << p + 1 << "\n";
        }
        else if (tip == 1) {
            int p = cb1(x, v, n);
            cout << p + 1 << "\n";
        }
        else {
            int p = cb2(x, v, n);
            cout << p + 1 << "\n";
        }
    }

    return 0;
}