Cod sursa(job #1517263)

Utilizator sirbu12Sirbu Claudiu sirbu12 Data 4 noiembrie 2015 00:14:01
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include<fstream>
using namespace std;
int a[10001];
int n,caz,s,nrx,poz,i,x;
int x0(int x)
{
    int st=1 , dr=n ;
    int  poz=-1;
    int m;
    while (st<=dr)
    {
        m=(st+dr)/2;
        if (x==a[m])
        {
            poz=m;
            st=m+1;

        }
        else
        if(x<a[m])
            dr=m-1;
        else
            st=m+1;
    }
    return poz;
}
int x1(int x)
{
    int st=1 , dr=n ,m;
    int  poz=-1;
    while (st<=dr)
    {
        m=(st+dr)/2;
        if (x>=a[m])
        {
            poz=m;
            st=m+1;

        }
        else
            dr=m-1;
    }
    return poz;
}

int x2(int x)
{
    int st=1 , dr=n ,m;
    int  poz=-1;
    while (st<=dr)
    {
        m=(st+dr)/2;
        if (x<=a[m])
        {
            poz=m;
            dr=m-1;

        }
        else
            st=m+1;

    }
    return poz;
}

int main()
{
    ifstream f("cautbin.in");
    ofstream g("cautbin.out");
    f>>n;
    for(i=1; i<=n; i++)
        f>>a[i];
    f>>nrx;
    for(i=1; i<=nrx; i++)
    {
        f>>caz;
        f>>x;
        if(caz==0)
            g<<x0(x)<<endl;
        if(caz==1)
            g<<x1(x)<<endl;
        if(caz==2)
            g<<x2(x)<<endl;

    }

    return 0;
}