Cod sursa(job #1576045)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 22 ianuarie 2016 00:38:51
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <cstdio>

#define NMax 100005
using namespace std;

int a[NMax],n,k,x,y;

int cautbin1(int lo,int hi, int x){
    int mij = (lo + hi) / 2;
    while(lo <= hi){
        mij = (lo + hi) / 2;
        if(a[mij] == x && a[mij + 1] != x){
            return mij;
        }else
        if(a[mij] >= x){
            hi = mij - 1;
        }else
        if(a[mij] < x){
            lo = mij + 1;
        }
    }
    return -1;
}
int cautbin2(int lo,int hi, int x){
    int mij = (lo + hi) / 2;
    while(lo <= hi){
        mij = (lo + hi) / 2;
        if(a[mij] <= x && a[mij + 1] > x){
            return mij;
        }
        if(a[mij] >= x){
            hi = mij - 1;
        }else
        if(a[mij] < x){
            lo = mij + 1;
        }
    }
}
int cautbin3(int lo,int hi, int x){
    int mij = (lo + hi) / 2;
    while(lo <= hi){
        mij = (lo + hi) / 2;
        if(a[mij] >= x && a[mij - 1] < x){
            return mij;
        }
        if(a[mij] > x){
            hi = mij - 1;
        }else
        if(a[mij] <= x){
            lo = mij + 1;
        }
    }
}
int main()
{
    freopen("cautbin.in","r",stdin);
    freopen("cautbin.out","w",stdout);
    scanf("%d",&n);
    for(int i = 1; i <= n; ++i){
        scanf("%d",&a[i]);
    }
    scanf("%d",&k);
    for(int i = 1; i <= k; ++i){
        scanf("%d%d",&x,&y);
        if(x == 0)
            printf("%d\n",cautbin1(1,n,y));
        if(x == 1)
            printf("%d\n",cautbin2(1,n,y));
        if(x == 2)
            printf("%d\n",cautbin3(1,n,y));
    }
    return 0;
}