Cod sursa(job #1700208)

Utilizator mihai.constantinConstantin Mihai mihai.constantin Data 9 mai 2016 20:09:13
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
using namespace std;

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

#define dmax 100005
#define L 18

int v[dmax];

int N, M;

int Binary_Search_0(int x)
{
    int i, pos;

    i = 0;
    pos = 1 << L;

    while(pos != 0)
    {
        if(i + pos <= N && v[i + pos] <= x) i += pos;

        pos /= 2;
    }

    if(v[i] == x) return i;
    else
        return -1;
}

int Binary_Search_1(int x)
{
    int i, pos;

    i = 0;
    pos = 1 << L;

    while(pos != 0)
    {
        if(i + pos <= N && v[i + pos] <= x) i += pos;

        pos /= 2;
    }

    return i;
}

int Binary_Search_2(int x)
{
    int i, pos;

    i = 0;
    pos = 1 << L;

    while(pos != 0)
    {
        if(i + pos <= N && v[i + pos] < x) i += pos;

        pos /= 2;
    }

    return i + 1;
}

void read()
{
    int tip, x;

    in >> N;

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

    in >> M;

    for(int i = 1; i <= M; i++)
    {
        in >> tip >> x;

        if(tip == 0) out << Binary_Search_0(x) << '\n';
        if(tip == 1) out << Binary_Search_1(x) << '\n';
        if(tip == 2) out << Binary_Search_2(x) << '\n';
    }
}

int main()
{
    read();

    return 0;
}