Cod sursa(job #2066061)

Utilizator mirunaFmiruna mirunaF Data 14 noiembrie 2017 18:00:11
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N=100001,L=15;
int  n ,v[N];

int caut_bin0(int x)
{
    int pas = 1<<L, r=0;
    while ( pas!=0)
    {
        if( pas+r <= n && v[r+pas] <= x)
        {
            r+=pas;
        }
        pas/=2;
    }
    if(v[r]!=x)
        return -1;
    else return r ;
}

int caut_bin2(int x)
{
    int pas = 1<<L, r=0;
    while ( pas!=0 )
    {
        if(pas+r < n && v[r+pas] < x)
        {
            r+= pas;
        }
        pas/=2;
    }
    return r+1;
}

int caut_bin1 (int x)
{
    int pas = 1<<L, r=0;
    while ( pas!=0)
    {
        if( pas+r <= n && v[r+pas] <= x)
        {
            r+=pas;
        }
        pas/=2;
    }
    return r ;
}

int main()
{
    int i,x, m,y;
    int (*f1)(int)=caut_bin1, (*f0)(int ) = caut_bin0, (*f2)(int ) = caut_bin2;
    in>>n;
    for(i=1; i<=n; i++)
        in>>v[i];
    in>>m;
    while(m!=0)
    {
        in>>y;
        in>>x;
        if(y==0)
            out<<f0(x)<<endl;
        else
        {
            if(y==1)
                out<<f1(x)<<endl ;
            else out<<f2(x)<<endl ;
        }
        m--;
    }
    return 0;
}