Cod sursa(job #2334577)

Utilizator radu_dumitruDumitru Radu Cosmin radu_dumitru Data 2 februarie 2019 18:27:19
Problema Cautare binara Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

unsigned long long v[100001];

int main()
{
    unsigned long long x;
    int n, m, i, op, poz, t;
    cin >> n;
    for (i = 1; i <= n; i++)
    {
        cin >> v[i];
    }
    sort(v + 1, v + n + 1);
    cin >> m;
    for (i = 0; i < m; i++)
    {
        cin >> op >> x;
        poz = 0;
        if (op == 0)
        {
            for (t = 1 << 20; t > 0; t = t >> 1)
            {
                if(poz + t <= n && v[poz + t] <= x)
                {
                    poz += t;
                }
            }
            if (v[poz] == x)
            {
                cout << poz << '\n';
            }
            else cout << -1 << '\n';
        }
        else if (op == 1)
        {
            for (t = 1 << 20; t > 0; t = t >> 1)
            {
                if(poz + t <= n && v[poz + t] - 1 <= x)
                {
                    poz += t;
                }
            }
            cout << poz << '\n';
        }
        else if (op == 2)
        {
            for (t = 1 << 20; t > 0; t = t >> 1)
            {
                if(poz + t <= n && v[poz + t] <= x - 1)
                {
                    poz += t;
                }
            }
            cout << poz  + 1 << '\n';
        }
    }
    return 0;
}