Cod sursa(job #1252688)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 31 octombrie 2014 00:22:57
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>

#define Nmax 100100

using namespace std;

int logN, N, M, A[Nmax];

int binarySearch(int type, int Value) {

    int i, Step;

    if(type == 2)
        Value--;

    Step = logN;

    for(i = 0; Step; Step >>= 1)
        if(i + Step <= N && A[i + Step] <= Value)
            i += Step;

    if(type == 0 && A[i] != Value)
        return -1;
    else
    if(type == 2)
        return (i + 1);

    return i;

}
void Read(ifstream & in) {

    in >> N;

    for(int i = 1; i <= N; i++)
        in >> A[i];

    in >> M;

}
int main() {

    int x, type;
    ifstream in("cautbin.in");
    ofstream out("cautbin.out");

    Read(in);

    for(logN = 1; logN <= N; logN <<= 1);

    while(M--) {

        in >> type >> x;
        out << binarySearch(type, x) << '\n';

        }

    in.close();
    out.close();

    return 0;
}