Cod sursa(job #1995496)

Utilizator DawlauAndrei Blahovici Dawlau Data 28 iunie 2017 02:32:31
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include<fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
const int NMAX=100005;
int v[NMAX],n,m;
int cb0(int x){
    int poz=0,st=1,dr=n;
    while(st<=dr){
        int mij=(st+dr)/2;
        if(v[mij]==x){
            poz=mij;
            st=mij+1;
        }
        else if(x<v[mij])
            dr=mij-1;
        else
            st=mij+1;
    }
    if(poz)
        return poz;
    return -1;
}
int cb1(int x){
    int poz,st=1,dr=n;
    while(st<=dr){
        int mij=(st+dr)/2;
        if(v[mij]<=x){
            poz=mij;
            st=mij+1;
        }
        else
            dr=mij-1;
    }
    return poz;
}
int cb2(int x){
    int poz,st=1,dr=n;
    while(st<=dr){
        int mij=(st+dr)/2;
        if(v[mij]>=x){
            poz=mij;
            dr=mij-1;
        }
        else
            st=mij+1;
    }
}
void citire(){
    int i;
    fin>>n;
    for(i=1;i<=n;++i)
        fin>>v[i];
}
void solve(){
    fin>>m;
    while(m--){
        int cod,x;
        fin>>cod>>x;
        if(cod==0)
            fout<<cb0(x)<<'\n';
        else if(cod==1)
            fout<<cb1(x)<<'\n';
        else
            fout<<cb2(x)<<'\n';
    }
}
int main(){
    citire();
    solve();
}