Cod sursa(job #1166515)

Utilizator DenisacheDenis Ehorovici Denisache Data 3 aprilie 2014 17:21:12
Problema Cautare binara Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <stdio.h>
using namespace std;
int v[100005],N,M,tipOp,i,x,j;
int cb0(int x,int L,int R)
{
    if (L>R) return -1;
    int M=(L+R)>>1;
    if (v[M]==x && v[M+1]>x) return M;
    else if (v[M]==x && v[M+1]==x) cb0(x,M+1,R);
    else if (v[M]<x) cb0(x,M+1,R);
    else if (v[M]>x) cb0(x,L,M-1);
}
int cb1(int x,int L,int R)
{
    if (L>R) return -1;
    int M=(L+R)>>1;
    if (v[M]<=x && v[M+1]>x) return M;
    else if (v[M]<=x && v[M+1]<=x) cb1(x,M+1,R);
    else if (v[M]<x) cb1(x,M+1,R);
    else if (v[M]>x) cb1(x,L,M-1);
}
int cb2(int x,int L,int R)
{
    if (L>R) return -1;
    int M=(L+R)>>1;
    if (v[M]>=x && v[M-1]<x) return M;
    else if (v[M]>=x && v[M-1]>=x) cb2(x,L,M-1);
    else if (v[M]<x) cb2(x,M+1,R);
    else if (v[M]>x) cb2(x,L,M-1);
}
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;
}