Cod sursa(job #1247972)

Utilizator deresurobertoFMI - Deresu Roberto deresuroberto Data 24 octombrie 2014 13:33:50
Problema Cautare binara Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include<fstream>
#define nx 100007
using namespace std;
int v[nx],n,m,i,q,x,poz,pas;

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

int binary_search_0(int left, int right,int val)
{
    poz=1,pas=(1<<30);

    while(pas>>=1)
        if(pas+poz<=n && v[poz+pas]<=val)
            poz+=pas;

    if(v[poz]==val)return poz;
    return -1;
}

int binary_search_1(int left,int right,int val)
{
    poz=1,pas=(1<<21);

    while(pas>>=1)
        if(poz+pas<=n && v[poz+pas]<=val)
            poz+=pas;

    return poz;
}

int binary_search_2(int left, int right,int val)
{
    poz=1,pas=(1<<21);

    while(pas>>=1)
        if(poz+pas<=n && v[poz+pas]<val)
            poz+=pas;

    return poz+1;
}

int main()
{
    fin>>n;
    for(i=1;i<=n;i++)
        fin>>v[i];

    fin>>m;
    for(i=1;i<=m;i++)
    {
        fin>>q>>x;
        if(q==0)
            fout<<binary_search_0(1,n,x)<<"\n";
        if(q==1)
            fout<<binary_search_1(1,n,x)<<"\n";
        if(q==2)
            fout<<binary_search_2(1,n,x)<<"\n";
    }

    return 0;
}