Cod sursa(job #864971)

Utilizator gabrielvGabriel Vanca gabrielv Data 25 ianuarie 2013 21:35:49
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <cstdio>
#include <algorithm>

#define NMAX 100005

using namespace std;

int N,M,X,v[NMAX],op,poz;

int main()
{

    freopen("cautbin.in","r",stdin);
    freopen("cautbin.out","w",stdout);

    scanf("%d",&N);

    for(int i=1;i<=N;i++)
        scanf("%d",&v[i]);

    sort(v + 1, v + N + 1);

    scanf("%d",&M);

    while(M--)
    {
        scanf("%d%d",&op,&X);
        if(op==0)
        {
            poz=upper_bound(v+1,v+N+1,X)-v-1;
            if(poz<=N && poz>=1 && v[poz] == X)
                printf("%d\n",poz);
            else
                printf("-1\n");
        }
        else
            if(op==1)
            {
                poz=lower_bound(v+1,v+N+1,X+1)-v-1;
                printf("%d\n",poz);
            }
            else
            {
                poz=upper_bound(v+1,v+N+1,X-1)-v;
                printf("%d\n",poz);
            }
    }
    return 0;
}