Cod sursa(job #2570160)

Utilizator cyg_Alex_codegicianBarbu Alexandru cyg_Alex_codegician Data 4 martie 2020 15:19:31
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda r3capitusulare Marime 1.18 kb
#include <fstream>
using namespace std;
ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");
const int nmax=100005;
int main()
{
    int n,a[nmax];
    fin >> n;
    for (int i=1;i<=n;i++)
    {
        fin >> a[i];
    }
    int t;
    fin >> t;
    while (t--)
    {
        int op,x,st=1,dr=n,rez=-1,mij;
        fin >> op >> x;
        if (op==0||op==1)
        {
            while (st<=dr)
            {
                mij=st+(dr-st)/2;
                if (a[mij]<=x)
                {
                    rez=mij;
                    st=mij+1;
                }
                else
                    dr=mij-1;
            }
            if (op==0)
            {
                if (a[rez]==x) fout << rez << '\n';
                else fout << -1 << '\n';
            }
            else if (op==1)
                fout << rez << '\n';
        }
        else if (op==2)
        {
            while (st<=dr)
            {
                mij=st+(dr-st)/2;
                if (a[mij]>=x)
                {
                    rez=mij;
                    dr=mij-1;
                }
                else
                    st=mij+1;
            }
            fout << rez << '\n';
        }
    }
}