Cod sursa(job #1990729)

Utilizator andrei1998xAndrei Ionut andrei1998x Data 13 iunie 2017 10:26:19
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include<fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int n,i,v[100001],nr,q,x,st,dr,mid,ok;
int main() {
    fin>>n;
    for(i=1;i<=n;i++)
        fin>>v[i];

    fin>>nr;

    for(i=1;i<=nr;i++){
        fin>>q>>x;
        if(q==0){
            st=1;
            dr=n;
            ok=0;
            while(st<=dr){
                mid=(st+dr)/2;

                if(v[mid]<=x){
                    st=mid+1;
                    if(v[mid]==x)
                        ok=1;
                }
                else
                    dr=mid-1;
            }

            if(ok==1)
                fout<<dr<<"\n";
            else
                fout<<-1<<"\n";
        }

        if(q==1){
            st=1;
            dr=n;
            while(st<=dr){
                mid=(st+dr)/2;

                if(v[mid]>x)
                    dr=mid-1;
                else
                    st=mid+1;
            }
            fout<<dr<<"\n";
        }

        if(q==2){
            st=1;
            dr=n;
            while(st<=dr){
                mid=(st+dr)/2;
                if(v[mid]>=x)
                    dr=mid-1;
                else
                    st=mid+1;
            }
            fout<<st<<"\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}