Cod sursa(job #2549839)

Utilizator Alin_StanciuStanciu Alin Alin_Stanciu Data 18 februarie 2020 06:57:00
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n, m, A[100002];

int Cb1(int x)
{
    int st = 1, dr = n;
    while (st <= dr)
    {
        int mij = (st + dr) / 2;
        if (A[mij] <= x)
            st = mij + 1;
        else dr = mij - 1;
    }
    return dr;
}

int Cb2(int x)
{
    int st = 1, dr = n;
    while (st <= dr)
    {
        int mij = (st + dr) / 2;
        if (A[mij] < x)
            st = mij + 1;
        else dr = mij - 1;
    }
    return st;
}

int main()
{
    fin >> n;
    for (int i = 1; i <= n; ++i)
        fin >> A[i];
    fin >> m;
    for (int i = 1; i <= m; ++i)
    {
        int c, x;
        fin >> c >> x;
        if (c == 0)
        {
            if (A[Cb1(x)] == x)
                fout << Cb1(x) << '\n';
            else fout << -1 << '\n';
        }
        else if (c == 1)
            fout << Cb1(x) << '\n';
        else fout << Cb2(x);
    }

    return 0;
}