Cod sursa(job #1166533)

Utilizator DenisacheDenis Ehorovici Denisache Data 3 aprilie 2014 17:33:57
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <stdio.h>
using namespace std;
int v[100005],N,M,tipOp,i,x,j;
int cb0(int x,int L,int R)
{
    int sol;
    while (L<=R)
    {
        int M=(L+R)>>1;
        if (v[M]>x) R=M-1;
        else sol=M,L=M+1;
    }
    if (v[sol]==x) return sol;
    return -1;
}
int cb1(int x,int L,int R)
{
    int sol;
    while (L<=R)
    {
        int M=(L+R)>>1;
        if (v[M]>x) R=M-1;
        else sol=M,L=M+1;
    }
    return sol;
}
int cb2(int x,int L,int R)
{
    int sol;
    while (L<=R)
    {
        int M=(L+R)>>1;
        if (v[M]>=x) sol=M,R=M-1;
        else L=M+1;
    }
    return sol;
}
int main()
{
    freopen("cautbin.in","r",stdin);
    freopen("cautbin.out","w",stdout);
    scanf("%d",&N);
    for (i=1;i<=N;i++) scanf("%d",&v[i]);
    scanf("%d",&M);
    for (i=1;i<=M;i++)
    {
        scanf("%d %d",&tipOp,&x);
        if (tipOp==0) printf("%d\n",cb0(x,1,N));
        else if (tipOp==1) printf("%d\n",cb1(x,1,N));
        else printf("%d\n",cb2(x,1,N));
    }
    return 0;
}