Cod sursa(job #811826)

Utilizator Mishu91Andrei Misarca Mishu91 Data 12 noiembrie 2012 22:56:32
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#include <vector>

using namespace std;

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

int N, M;
vector <int> V;

void read() {
    fin >> N;

    for(int i = 0; i < N; i++) {
        int x;
        fin >> x;
        V.push_back(x);
    }
}

// A[lo] <= val < A[hi]
int cbin1(int type, int val) {
    int lo = -1, hi = N;

    while (hi - lo > 1) {
        int mid = (hi + lo) / 2;

        if (V[mid] <= val) {
            lo = mid;
        } else {
            hi = mid;
        }
    }

    if (type == 0 && V[lo] != val) {
        return -1;
    }

    return lo + 1;
}


// A[lo] < val <= A[hi]
int cbin2(int type, int val) {
    int lo = -1, hi = N;

    while (hi - lo > 1) {
        int mid = (hi + lo) / 2;

        if (val <= V[mid]) {
            hi = mid;
        } else {
            lo = mid;
        }
    }

    return hi + 1;
}

int main() {
    read();

    fin >> M;

    while (M--) {
        int type, val;
        fin >> type >> val;

        if (type == 0 || type == 1) {
            fout << cbin1(type, val) << "\n";
        } else {
            fout << cbin2(type, val) << "\n";
        }
    }
    return 0;
}