Cod sursa(job #2115618)

Utilizator horea4Cenan Horea horea4 Data 26 ianuarie 2018 22:26:13
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int n,v[100000],M,x,q;
int q0(int x)
{
    int m,s=1,d=n,poz=0;
    while(s<=d&&poz==0)
    {
        m=(s+d)/2;
        if(v[m]==x)
            poz=m;
        else if (x<v[m])
            d=m-1;
            else s=m+1;
    }
    if(poz==0)
        poz=-1;
    return poz;
}
int q1(int x)
{
    int m,s=1,d=n,poz=0;
    while(s<=d&&poz==0)
    {
        m=(s+d)/2;
        if(v[m]<=x)
            poz=m;
        else if (x<v[m])
            d=m-1;
            else s=m+1;
    }

    return poz;
}
int q2(int x)
{
    int m,s=1,d=n,poz=0;
    while(s<=d&&poz==0)
    {
        m=(s+d)/2;
        if(v[m]>=x)
            poz=m;
        else if (x<v[m])
            d=m-1;
            else s=m+1;
    }

    return poz;
}

int main()
{
    f>>n;
    for(int i=1;i<=n;i++)
        f>>v[i];
    f>>M;
    while(M!=0)
    {
        f>>q>>x;
        switch(q)
        {
            case 0:
                g<<q0(x)<<endl;
            case 1:
                g<<q1(x)<<endl;
            case 2:
                g<<q2(x)<<endl;

        }
        M--;


    }


    return 0;
}