Cod sursa(job #2951810)

Utilizator AndreibatmanAndrei Croitoriu Andreibatman Data 7 decembrie 2022 12:47:58
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int n,v[100010],i,q,x,op;
int cb1(int x)
{
    int st=1,dr=n,mij,best=-1;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        if(v[mij]<=x)
        {
            if(v[mij]==x)
                best=mij;
            st=mij+1;
        }
        else dr=mij-1;
    }
    return best;
}
int cb2(int x)
{
    int st=1,dr=n,mij,best=-1;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        if(v[mij]<=x)
        {
            best=mij;
            st=mij+1;
        }
        else dr=mij-1;
    }
    return best;
}
int cb3(int x)
{
    int st=1,dr=n,mij,best=-1;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        if(v[mij]>=x)
        {
            best=mij;
            dr=mij-1;
        }
        else st=mij+1;
    }
    return best;
}
int main()
{
    fin>>n;
    for(i=1;i<=n;i++)
        fin>>v[i];
    fin>>q;
    while(q--)
    {
        fin>>op>>x;
        if(op==0)
            fout<<cb1(x)<<'\n';
        else if(op==1)
            fout<<cb2(x)<<'\n';
        else
            fout<<cb3(x)<<'\n';
    }
    return 0;
}