Cod sursa(job #855141)

Utilizator blechereyalBlecher Eyal blechereyal Data 14 ianuarie 2013 18:21:52
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#define NMAX 100001
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int V[NMAX],N,M;

int cautbin(int x,int s,int d)
{
    if (s>d) return -1;
        else
            {
            int m;
            m=(s+d)/2;
            if (x==V[m]) return m;
                else if (x>V[m]) cautbin(x,m+1,d);
                        else cautbin(x,s,m-1);
            }

}

int cautbin1(int x,int s,int d)
{int m;
    if (s>d) return m;
        else
            {
                m=(s+d)/2;
                if (x>V[m]) cautbin(x,m+1,d);
                    else cautbin(x,s,m-1);
            }
}
int cautbin2(int x,int s,int d)
{int m;
    if (s>d) return m;
        else
            {
                m=(s+d)/2;
                if (x>=V[m]) cautbin(x,m+1,d);
                    else cautbin(x,s,m-1);
            }

}




int main()
{
    int m,op,i,x;
    f>>N;
    for (i=1;i<=N;i++)
        f>>V[i];
    f>>M;
    for (i=1;i<=M;i++)
        {
        f>>op>>x;
        switch (op)
            {
            case 0:
            m=cautbin(x,1,N);
            while (V[m]==x) m++;
            g<<m-1<<"\n";
            break;
            case 1:
            m=cautbin1(x,1,N);
            while (V[m]<=x) m++;
            g<<m-1<<"\n";
            break;
            case 2:
            m=cautbin2(x,1,N);
            while (V[m]>=x) m--;
            g<<m+1<<"\n";
            break;
            }
        }
    return 0;
}