Cod sursa(job #1593026)

Utilizator malina_floreaMalina Florea malina_florea Data 8 februarie 2016 11:22:23
Problema Cautare binara Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#define DMAX 100005
using namespace std;
ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");

void citire();
int f0(int);
int f1(int);
int f2(int);

int n;
long long int v[DMAX];

int main()
{
    int i, com, x, m;
    
    citire();
    
    fin>> m;
    for (i=0; i<m; i++)
    {
        fin>> com>> x;
        if (com==0) fout<< f0(x)+1<< '\n';
        if (com==1) fout<< f1(x)+1<< '\n';
        if (com==2) fout<< f2(x)+1<< '\n';
    }
    
    fin.close();
    fout.close();
    return 0;
}

void citire()
{
    int i;
    fin>> n;
    for (i=0; i<n; i++) fin>> v[i];
}

int f0(int x)
{
    int st=-1, dr=n, mij=0;
    
    while (dr-st>1)
    {
        mij=(dr+st)/2;
        if (v[mij]<=x)
            st=mij;
            else
            dr=mij;
    }
    
    if (st!=-1 && v[st]==x) return st;
    return -2;
}

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

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