Cod sursa(job #2033044)

Utilizator ifrimencoAlexandru Ifrimenco ifrimenco Data 6 octombrie 2017 08:13:09
Problema Cautare binara Scor 60
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, A[100002];

int binary1(int val)
{
    int i, step;
    for (step = 1; step < N; step <<= 1);
    for (i = 0; step; step >>= 1)
        if (i + step < N && A[i + step] <= val)
           i += step;
    if (A[i] != val) return -1;
    return i;
}

int binary2(int val)
{
    int i, step;
    for (step = 1; step < N; step <<= 1);
    for (i = 0; step; step >>= 1)
        if (i + step < N && A[i + step] <=  val)
           i += step;
    return i;
}

int binary3(int val)
{
    int i, step;
    for (step = 1; step < N; step <<= 1);
    for (i = 0; step; step >>= 1)
        if (i + step < N && A[i + step] <  val)
           i += step;
    return i + 1;
}

int main()
{
    int i;
    f >> N;
    for (i = 1; i <= N; ++i) f >> A[i];
    int M;
    f >> M;
    int x, y;
    for (i = 1; i <= M; ++i) {
            f >> x >> y;
    if (x == 0) g << binary1(y) << "\n";
    if (x == 1) g << binary2(y) << "\n";
    if (x == 2) g << binary3(y) << "\n";

    }
    return 0;
}