Cod sursa(job #2283048)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 14 noiembrie 2018 21:47:33
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int n,a[100001],q,op,x;
int cautare_binara0()
{
    int st,dr,poz,mij;
    st=1;
    dr=n;
    poz=-1;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        if(a[mij]==x)
        {
            poz=mij;
            st=mij+1;
        }
        else
        {
            if(a[mij]<x)
            {
                st=mij+1;
            }
            else
            {
                dr=mij-1;
            }
        }
    }
    return poz;
}
int cautare_binara1()
{
    int st,dr,poz,mij;
    st=1;
    dr=n;
    poz=1;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        if(a[mij]<=x)
        {
            poz=mij;
            st=mij+1;
        }
        else
        {
            dr=mij-1;
        }
    }
    return poz;
}
int cautare_binara2()
{
    int st,dr,poz,mij;
    st=1;
    dr=n;
    poz=n;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        if(a[mij]>=x)
        {
            poz=mij;
            dr=mij-1;
        }
        else
        {
            st=mij+1;
        }
    }
    return poz;
}
int main()
{
    int i;
    f>>n;
    for(i=1;i<=n;i++)
    {
        f>>a[i];
    }
    f>>q;
    while(q--)
    {
        f>>op>>x;
        if(op==0)
            g<<cautare_binara0()<<"\n";
        if(op==1)
            g<<cautare_binara1()<<"\n";
        if(op==2)
            g<<cautare_binara2()<<"\n";
    }
    return 0;
}