Cod sursa(job #2703545)

Utilizator cyg_mihaizMIHAI ZARAFIU cyg_mihaiz Data 8 februarie 2021 18:55:05
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <algorithm>

using namespace std;
const int NMAX = 100000;

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

int v[NMAX + 5];

inline bool check(int i, int n)
{
    return (1 <= i and i <= n);
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(NULL);

    int n,i,m,x,y,poz;
    fin >> n;
    for(i = 1; i <= n; i++)
        fin >> v[i];
    sort(v + 1, v + n + 1);
    fin >> m;
    while(m--)
    {
        fin >> x >> y;
        if(!x)
        {
            poz = upper_bound(v + 1, v + n + 1, y) - v - 1;
            if(check(poz, n) and v[poz] == y)
                fout << poz << "\n";
            else
                fout << "-1\n";
        }
        else
            if(x == 1)
            {
                poz = lower_bound(v + 1, v + n + 1, y + 1) - v - 1;
                fout << poz << "\n";
            }
            else
            {
                poz = upper_bound(v + 1, v + n + 1, y - 1) - v;
                fout << poz << "\n";
            }
    }
    return 0;
}