Cod sursa(job #2117224)

Utilizator cata_albuCatalin Albu cata_albu Data 28 ianuarie 2018 18:11:04
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 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;
        if(q==0)
            g<<q0(x);
        else if(q==1)
            g<<q1(x);
        else if(q==2)
            g<<q2(x);


        M--;


    }


    return 0;
}