Cod sursa(job #3298624)

Utilizator Daniel15022012Daniel Munteanu Daniel15022012 Data 31 mai 2025 18:54:42
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

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

    int N;
    fin >> N;
    vector<int> v(N);
    for (int i = 0; i < N; ++i) {
        fin >> v[i];
    }

    int M;
    fin >> M;

    for (int i = 0; i < M; ++i) {
        int tip, x;
        fin >> tip >> x;

        if (tip == 0) {
            // Cea mai mare pozitie unde v[i] == x
            auto it = upper_bound(v.begin(), v.end(), x);
            if (it == v.begin() || *(it - 1) != x)
                fout << -1 << '\n';
            else
                fout << (it - v.begin() - 1 + 1) << '\n'; // +1 pentru indexare de la 1
        }
        else if (tip == 1) {
            // Cea mai mare pozitie unde v[i] <= x
            auto it = upper_bound(v.begin(), v.end(), x);
            fout << (it - v.begin() - 1 + 1) << '\n'; // +1 pentru indexare de la 1
        }
        else if (tip == 2) {
            // Cea mai mica pozitie unde v[i] >= x
            auto it = lower_bound(v.begin(), v.end(), x);
            fout << (it - v.begin() + 1) << '\n'; // +1 pentru indexare de la 1
        }
    }

    return 0;
}