Cod sursa(job #3272430)

Utilizator bogdanoancea68Bogdan Oancea bogdanoancea68 Data 29 ianuarie 2025 13:03:50
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

const int MAX_N = 100000;

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

int arr[MAX_N];

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

    int n, m, c, x;
    fin >> n;
    
    // Read array
    for (int i = 0; i < n; i++) {
        fin >> arr[i];
    }

    fin >> m;

    // Process queries
    while (m--) {
        fin >> c >> x;
        
        if (c == 0) {
            // Last occurrence of x (or -1 if not found)
            int pos = upper_bound(arr, arr + n, x) - arr - 1;
            if (pos >= 0 && arr[pos] == x) fout << pos + 1 << '\n';
            else fout << "-1\n";
        } 
        else if (c == 1) {
            // Last position where arr[i] ≤ x
            int pos = upper_bound(arr, arr + n, x) - arr - 1;
            fout << pos + 1 << '\n';
        } 
        else {
            // First position where arr[i] ≥ x
            int pos = lower_bound(arr, arr + n, x) - arr;
            fout << pos + 1 << '\n';
        }
    }

    return 0;
}