Cod sursa(job #1494623)

Utilizator doroftei1999Doroftei Andrei doroftei1999 Data 1 octombrie 2015 17:07:29
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda pregatire_cl.10_cnpr Marime 1.88 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int bsearch0(int v[],int x,int n)
{
    int st,dr,mij,gasit;
    st=1;
    dr=n;
    gasit=0;
    while (gasit==0 && st<=dr)
    {
        mij=(st+dr)/2;
        if (x==v[mij])
        {
            gasit=1;
            while (x==v[mij])
                mij++;
            return mij-1;
        }
        else
            if (x<=v[mij])
                dr=v[mij-1];
            else
                st=v[mij+1];
    }
    return -1;
}
int bsearch1(int v[],int x,int n)
{
    int st,dr,mij,gasit;
    st=1;
    dr=n;
    gasit=0;
    while (gasit==0 && st<=dr)
    {
        mij=(st+dr)/2;
        if (v[mij]<=x)
        {
            while (v[mij]<=x)
                mij++;
            return mij-1;
        }
        else
            if (x<=v[mij])
                dr=v[mij-1];
            else
                st=v[mij+1];
    }
    return -1;
}
int bsearch2(int v[],int x,int n)
{
    int st,dr,mij,gasit;
    st=1;
    dr=n;
    gasit=0;
    while (gasit==0 && st<=dr)
    {
        mij=(st+dr)/2;
        if (x<=v[mij])
        {
            while (x<=v[mij])
                mij--;
            return mij+1;
        }
        else
            if (x<=v[mij])
                dr=v[mij-1];
            else
                st=v[mij+1];
    }
    return -1;
}
int main()
{
    int n,m,i,y,x;
    f>>n;
    int v[n];
    for (i=1;i<=n;i++)
        f>>v[i];
    f>>m;
    for (i=1;i<=m;i++)
    {
        f>>y;
        if (y==0)
        {
            f>>x;
            g<<bsearch0(v,x,n)<<endl;
        }
        if (y==1)
        {
            f>>x;
            g<<bsearch1(v,x,n)<<endl;
        }
        if (y==2)
        {
            f>>x;
            g<<bsearch2(v,x,n)<<endl;
        }
    }
    return 0;
}