Cod sursa(job #1804615)

Utilizator Stefania189StefaniaB Stefania189 Data 12 noiembrie 2016 20:09:08
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int n,m,a[100001],dr,st,p,i,mij,x,ok;
int main ()
{
    f>>n;
    for(i=1;i<=n;++i) f>>a[i];
    f>>m;
    for(i=1;i<=m;++i) {
        f>>p>>x;
        if(p==0) {
            st=0;
            dr=n;
            while(dr-st>1) {
                mij=(st+dr)>>1;
                if(a[mij]>x) dr=mij;
                else st=mij;
            }
            if(x==a[st]) g<<st<<"\n";
        }
        else if(p==1){
            st=0;
            dr=n;
            while(dr-st>1) {
                mij=(st+dr)>>1;
                if(a[mij]<x) dr=mij;
                else st=mij;
            }
            if(x>=a[st]) g<<st<<"\n";
        }
        else {
            st=0;
            dr=n;
            ok=0;
            while(dr-st>1 && !ok) {
                mij=(st+dr)>>1;
                if(a[mij]>x) dr=mij;
                else st=mij;
                if(x<=a[st]) {
                    g<<st<<"\n";
                    ok=1;
                }
            }
        }
    }
    return 0;
}