Cod sursa(job #1459343)

Utilizator moise_alexandruMoise Alexandru moise_alexandru Data 9 iulie 2015 16:55:31
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

const int maxn=100005;

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

int v[maxn];
int n, m;

int cautare0(int x)
{
    int st=1;
    int dr=n;
    int rez=-1;
    while(st<=dr)
    {
        int mij=(st+dr)/2;
        if(x<v[mij])
            dr=mij-1;
        else if(x>v[mij])
            st=mij+1;
        else
        {
            rez=mij;
            st=mij+1;
        }
    }
    return rez;
}

int cautare1(int x)
{
    int st=1;
    int dr=n;
    int rez=-1;
    while(st<=dr)
    {
        int mij=(st+dr)/2;
        if(v[mij]<=x)
        {
            rez=mij;
            st=mij+1;
        }
        else
            dr=mij-1;
    }
    return rez;
}

int cautare2(int x)
{
    int st=1;
    int dr=n;
    int rez=-1;
    while(st<=dr)
    {
        int mij=(st+dr)/2;
        if(v[mij]>=x)
        {
            rez=mij;
            dr=mij-1;
        }
        else
            st=mij+1;
    }
    return rez;
}

int main()
{
    in>>n;
    for(int i=1;i<=n;i++)
        in>>v[i];
    in>>m;
    for(int i=1;i<=m;i++)
    {
        int op;
        in>>op;
        int x;
        in>>x;
        if(op==0)
            out<<cautare0(x);
        else if(op==1)
            out<<cautare1(x);
        else if(op==2)
            out<<cautare2(x);
        out<<"\n";
    }
    return 0;
}