Cod sursa(job #1681714)

Utilizator tudormaximTudor Maxim tudormaxim Data 9 aprilie 2016 17:46:04
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");

const int nmax = 1e5+5;
int v[nmax], n;

void bsearch0(int val) {
    int st=1, dr=n, mij, poz=-1;
    while(st<=dr) {
        mij=(st+dr)>>1;
        if(v[mij]<=val) {
            st=st+1;
            poz=mij;
        }
        else dr=mij-1;
    }
    if(v[poz]==val) fout << poz << "\n";
    else fout << "-1\n";
}

void bsearch1(int val) {
    int st=1, dr=n, poz, mij;
    while(st<=dr) {
        mij=(st+dr)>>1;
        if(v[mij]<=val) {
            poz=mij;
            st=mij+1;
        }
        else dr=mij+-1;
    }
    fout << poz << "\n";
}

void bsearch2(int val) {
    int st=1, dr=n, poz, mij;
    while(st<=dr) {
        mij=(st+dr)>>1;
        if(v[mij]>=val) {
            poz=mij;
            dr=mij-1;
        }
        else st=mij+1;
    }
    fout << poz << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    int i, op, x, m;
    fin >> n;
    for(i=1; i<=n; i++)
        fin >> v[i];
    fin >> m;
    for(i=1; i<=m; i++) {
        fin >> op >> x;
        if(op==0) bsearch0(x);
        else if(op==1) bsearch1(x);
        else bsearch2(x);
    }
    fin.close();
    fout.close();
    return 0;
}