Cod sursa(job #2101446)

Utilizator Sebi01Who This Sebi01 Data 7 ianuarie 2018 16:01:51
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include<fstream>
using namespace std;
ifstream cin("cautbin.in");
ofstream cout("cautbin.out");
int n,a[100030],m,x,y,st,dr,p;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];
    cin>>m;
    while(m--){
     cin>>x;
     if(x==0){cin>>y;
        st=1;
        dr=n;
        while(st<=dr){
            p=(st+dr)/2;
            if(a[p]<=y)st=p+1;
            else dr=p-1;
        }
        p=(st+dr)/2;
        if(a[p]>y)p--;
        if(a[p]==y)cout<<p<<"\n";
        else cout<<"-1\n";
        }
     if(x==1){cin>>y;
        st=1;
        dr=n;
        while(st<dr){
            p=(st+dr)/2;
            if(a[p]<=y)st=p+1;
            else dr=p-1;
        }
        p=(st+dr)/2;
        if(a[p]>y)p--;
        if(a[p]<=y)cout<<p<<"\n";
        }
     if(x==2){cin>>y;
        st=1;
        dr=n;
        while(st<dr){
            p=st+dr;
            p/=2;
            if(a[p]<y)st=p+1;
            else dr=p-1;
         }
         p=st+dr;
         p/=2;
         if(a[p]<y)p++;
         cout<<p<<"\n";
     }
    }
}