Cod sursa(job #2782821)

Utilizator RaresVilcuVilcu Rares Andrei RaresVilcu Data 13 octombrie 2021 10:02:41
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int v[10001], n, x, k, nr1, nr2;

int _0 (int x)
{
    int st=1;
    int dr=n;
    int poz=-1;

    while(st<=dr)
    {
        int mij=(st+dr)/2;

        if(v[mij]>x)
        {
            dr=mij-1;
        }
        else
        {
            if(v[mij]==x)
            poz=mij;
            st=mij+1;
        }

    }
    return poz;
}

int _1 (int x)
{
    int st=1;
    int dr=n;
    int poz=-1;

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

int _2 (int x)
{
    int st=1;
    int dr=n;
    int poz=-1;

    while(st<=dr)
    {
        int mij=(st+dr)/2;
        if(v[mij]>=x)
        {
            poz=mij;
            dr=mij-1;
        }
        else
            st=mij+1;
    }
    return poz;
}
int main()
{
    fin>>n;
    for(int i=1;i<=n;i++)
        fin>>v[i];
    fin>>k;
    while(k)
    {
        fin>>nr1>>nr2;
        if(nr1==0)
            fout<< _0(nr2)<<'\n';
        else if(nr1==1)
            fout<< _1(nr2)<<'\n';
        else fout<< _2(nr2)<<'\n';
        k--;
    }

    return 0;
}