Cod sursa(job #566055)

Utilizator bogfodorBogdan Fodor bogfodor Data 28 martie 2011 16:52:46
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <iostream>
#include <cstdio>
#define Lmax 100005

using namespace std;

int n, a[Lmax];
int q;

void cauta(int x)
{
    int st=0,dr=n-1;
    while(st!=dr)
    {
        int mid=(st+dr)/2;
        if(a[mid]==x){
            while(a[mid]==x)
                mid++;
            printf("%d\n",mid);
            return;
        }
        if(x>a[mid])
            st=mid+1;
        else
            dr=mid;
    }

}

void cauta2(int x)
{
    int st=0,dr=n-1;
    while(st!=dr)
    {
        int mid=(st+dr)/2;
        if(a[mid]==x){
            while(a[mid]<=x)
                mid++;
            printf("%d\n",mid);
            return;
        }
        if(x>a[mid])
            st=mid+1;
        else
            dr=mid;
    }
}

void cauta3(int x)
{
    int st=0,dr=n-1;
    while(st!=dr)
    {
        int mid=(st+dr)/2;
        if(a[mid]==x){
            while(a[mid]>=x)
                mid--;
            printf("%d\n",mid+2);
            return;
        }
        if(x>a[mid])
            st=mid+1;
        else
            dr=mid;
    }
}

void citire()
{
    freopen("cautbin.in","r",stdin);
    freopen("cautbin.out","w",stdout);
    scanf("%d ",&n);
    for(int i=0;i<n;i++)
        scanf("%d ",&a[i]);
    scanf("%d ",&q);
    for(int i=0;i<q;i++)
    {
        int c,p;
        scanf("%d %d ", &c, &p);
        if(c==0)
            cauta(p);
        else
            if(c==1)
                cauta2(p);
            else
                cauta3(p);
    }
}

int main()
{
    citire();
    return 0;
}