Cod sursa(job #2794796)

Utilizator guzgandemunteIonescu Laura guzgandemunte Data 5 noiembrie 2021 14:23:49
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#define NMAX 100000

using namespace std;

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

int n, m;
int v[NMAX];

int cautBinRightmost(int x, int st, int dr)
{
    int middle;
    dr++;
    while (dr - st > 1) {
        middle = st + (dr - st) / 2;
        if (x < v[middle]) dr = middle;
        else st = middle;
    }
    return st;
}

int cautBinLeftmost(int x, int st, int dr)
{
    int middle;
    st--;
    while (dr - st > 1) {
        middle = st + (dr - st) / 2;
        if (x > v[middle]) st = middle;
        else dr = middle;
    }
    return dr;
}

int main()
{
    fin >> n;

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

    fin >> m;

    int opt, x, y;
    while (m--) {
        fin >> opt >> x;
        if (opt == 0) {
            y = cautBinRightmost(x, 0, n - 1);
            fout << (v[y] == x ? y + 1 : -1);
        }
        else if (opt == 1) fout << cautBinRightmost(x, 0, n - 1) + 1;
        else fout << cautBinLeftmost(x, 0, n - 1) + 1;
        fout << '\n';
    }

    fin.close();
    fout.close();
    return 0;
}