Cod sursa(job #566034)

Utilizator TeodoraTanaseTeodora Tanase TeodoraTanase Data 28 martie 2011 16:40:16
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <cstdio>
#include <algorithm>

using namespace std;

const int M=100005;
int n, m, a[M], q, x, maxpoz;

void dreapta()
{
    int st=0, dr=n-1;
    while (st<=dr)
    {
        int mij=(st+dr)/2;
        if (x==a[mij])
        {
            maxpoz=max(maxpoz,mij);
            st=mij+1;
        }
        else if (x<a[mij])
            dr=mij-1;
        else
            st=mij+1;

    }
}

void maimicegal()
{
    int st=0, dr=n-1;
    while (st<=dr)
    {
        int mij=(st+dr)/2;
        if (a[mij]<=x)
        {
            maxpoz=max(maxpoz,mij);
            st=mij+1;
        }
        else
            dr=mij-1;
    }
}

void maimareegal()
{
    int st=0, dr=n-1;
    while (st<=dr)
    {
        int mij=(st+dr)/2;
        if (a[mij]>=x)
        {
            maxpoz=min(maxpoz,mij);
            dr=mij-1;
        }
        else
            st=mij+1;
    }
}

void citire()
{
    scanf ("%d ",&n);
    for (int i=0; i<n; i++)
        scanf ("%d ",&a[i]);
    scanf ("%d ",&m);
    for (int i=0; i<m; i++)
    {
        scanf ("%d %d ",&q,&x);
        if (q==0)
        {
            maxpoz=-1;
            dreapta();
            printf ("%d\n",maxpoz+1);
        }
        else if (q==1)
        {
            maxpoz=-1;
            maimicegal();
            printf ("%d\n",maxpoz+1);
        }
        else
        {
            maxpoz=n;
            maimareegal();
            printf ("%d\n",maxpoz+1);
        }
    }
}

int main()
{
    freopen ("cautbin.in","r",stdin);
    freopen ("cautbin.out","w",stdout);
    citire();
    return 0;
}