Cod sursa(job #2857855)

Utilizator AdelaCorbeanuAdela Corbeanu AdelaCorbeanu Data 26 februarie 2022 14:53:01
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <vector>

using namespace std;

int n;

int lower (const vector<int> &v, const int x) {
    int pow = 1 << 30;
    int poz = n - 1;

    while (pow) {
        if (poz - pow >= 0 && v[poz - pow] >= x) poz -= pow;
        pow /= 2;
    }

    return poz;
}

int upper (const vector<int> &v, const int x) {
    int pow = 1 << 30;
    int poz = 0;

    while (pow) {
        if (poz + pow < n && v[poz + pow] <= x) poz += pow;
        pow /= 2;
    }

    return poz;
}

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

    fin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; ++i) fin >> a[i];

    int t, task, nr;
    fin >> t;

    while (t) {
        fin >> task >> nr;

        if (task < 2) {
            int up = upper(a, nr);
            fout << ((!task && a[up] != nr) ? -1 : up + 1) << '\n';
        }

        else fout << lower(a, nr) + 1 << '\n';
        t--;
    }
    return 0;
}