Cod sursa(job #1380267)

Utilizator hopingsteamMatraguna Mihai-Alexandru hopingsteam Data 7 martie 2015 05:09:42
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include    <iostream>
#include    <fstream>

using namespace std;

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

const int NMax = 100005;
int V[NMax], N, M;

int BinSearch0(int x)
{
    int Sol = -1, Left = 1, Right = N;
    while(Left <= Right)
    {
        int Mid = (Left+Right) >> 1;
        if(V[Mid] == x)
        {
            Sol =   Mid;
            Left =  Mid + 1;
        }
        if(V[Mid] > x)
            Right = Mid - 1;
        if(V[Mid] < x)
            Left =  Mid + 1;
    }
    return Sol;
}

int BinSearch1(int x)
{
    int Sol = -1, Left = 1, Right = N;
    while(Left <= Right)
    {
        int Mid = (Left+Right) >> 1;
        if(V[Mid] <= x)
        {
            Sol =   Mid;
            Left =  Mid + 1;
        }
        if(V[Mid] > x)
            Right = Mid - 1;
    }
    return Sol;
}

int BinSearch2(int x)
{
    int Sol = -1, Left = 1, Right = N;
    while(Left <= Right)
    {
        int Mid = (Left+Right) >> 1;
        if(V[Mid] >= x)
        {
            Sol =    Mid;
            Right =  Mid - 1;
        }
        if(V[Mid] < x)
            Left =  Mid + 1;
    }
    return Sol;
}

void Read()
{
    fin >> N;
    for(int i = 1; i <= N; i++)
        fin >> V[i];

    fin >> M;
    for(int i = 1; i <= M; i++)
    {
        int op, x;
        fin >> op >> x;
        if(op == 0)
            fout << BinSearch0(x) << "\n";
        if(op == 1)
            fout << BinSearch1(x) << "\n";
        if(op == 2)
            fout << BinSearch2(x) << "\n";

    }
}

int main()
{
    Read();
    return 0;
}