Cod sursa(job #2162174)

Utilizator vladb21Borcan Vlad vladb21 Data 12 martie 2018 08:41:36
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <stdio.h>

int a[100001],n;

int f0(int x)
{
    int mij,st,dr,poz;
    poz=-1;
    st=1;
    dr=n;
    while(st<=dr)
    {
        mij=st+(dr-st)/2;
        if(x==a[mij])
        {
            poz=mij;
            st=mij+1;
        }
        else
        {
            if(x<a[mij])
                dr=mij-1;
            else
                st=mij+1;
        }
    }
    return poz;
}

int f1(int x)
{
    int mij,st,dr,poz;
    poz=-1;
    st=1;
    dr=n;
    while(st<=dr)
    {
        mij=st+(dr-st)/2;
        if(a[mij]<=x)
        {
            poz=mij;
            st=mij+1;
        }
        else
        {
            dr=mij-1;
        }
    }
    return poz;
}

int f2(int x)
{
    int mij,st,dr,poz;
    poz=-1;
    st=1;
    dr=n;
    while(st<=dr)
    {
        mij=st+(dr-st)/2;
        if(a[mij]>=x)
        {
            poz=mij;
            dr=mij-1;
        }
        else
        {
            st=mij+1;
        }
    }
    return poz;
}




int main()
{
    int x,i,c,m,st,dr,mij;
    FILE *f,*g;
    f=fopen("cautbin.in","r");
    g=fopen("cautbin.out","w");
    fscanf(f,"%d",&n);
    for(i=1;i<=n;i++)
        fscanf(f,"%d",&a[i]);
    fscanf(f,"%d",&m);
    for(i=1;i<=m;i++)
    {
        fscanf(f,"%d%d",&c,&x);
        if(c==0)
            fprintf(g,"%d\n",f0(x));
        if(c==1)
            fprintf(g,"%d\n",f1(x));
        if(c==2)
            fprintf(g,"%d\n",f2(x));
    }


    fclose(f);
    fclose(g);
}