Cod sursa(job #1385188)

Utilizator pepsiM4A1Ozturk Arif pepsiM4A1 Data 11 martie 2015 19:11:35
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <cstdio>
int n,m;
int a[100001];
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]);
    int tip,nr;
    scanf("%d",&m);
    for(int x=1;x<=m;x++)
    {
        scanf("%d%d",&tip,&nr);
        if(tip==0)
        {
            int pos=-1,s=1,e=n;
            while(s<=e)
            {
                int mij=(s+e)/2;
                if(a[mij]==nr)
                {
                    pos=mij;
                    s=mij+1;
                }
                else if(a[mij]<nr) s=mij+1;
                else e=mij-1;
            }
            printf("%d\n",pos);
        }
        else if(tip==1)
        {
            int pos,s=1,e=n;
            while(s<=e)
            {
                int mij=(s+e)/2;
                if(a[mij]<=nr)
                {
                    pos=mij;
                    s=mij+1;
                }
                else e=mij-1;
            }
            printf("%d\n",pos);
        }
        else if(tip==2)
        {
            int pos,s=1,e=n;
            while(s<=e)
            {
                int mij=(s+e)/2;
                if(a[mij]>=nr)
                {
                    pos=mij;
                    e=mij-1;
                }
                else s=mij+1;
            }
            printf("%d\n",pos);
        }
    }
}