Cod sursa(job #2866455)

Utilizator GargantuanRoOprea Rares GargantuanRo Data 9 martie 2022 18:36:42
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
using namespace std;

ifstream cin("cautbin.in");
ofstream cout("cautbin.out");

const int nmax = 200001;
int v[nmax], n, t;

int cb(int x)
{
    int st = 1, dr = n, ans = 0;
    while(st <= dr)
    {
        int mij = st + (dr - st) / 2;
        if(v[mij] <= x)
        {
            st = mij + 1;
            ans = mij;
        }
        else
            dr = mij - 1;
    }
    if(t == 0)
    {
        if( v[ans] == x )
            return ans;
        return -1;
    }
    return ans;
    /// last occurance of x or the maximum smaller element
}

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