Cod sursa(job #306347)

Utilizator alexandru92alexandru alexandru92 Data 20 aprilie 2009 14:40:48
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include<stdio.h>
#include<stdlib.h>
int main(void)
  {int *v,n,m,q,x,st,dr,mid,poz;
   	freopen("cautbin.in","rt",stdin);
      freopen("cautbin.out","wt",stdout);
      scanf("%d",&n); v=(int*)calloc(n+1,sizeof(n));
      for(register int i=1;i<=n;++i) scanf("%d",&v[i]);
      scanf("%d",&m);
      while(m--)
           {scanf("%d%d",&q,&x);
            poz=-1; dr=n; st=1;
            while(dr>=st)
                 {
                  mid=st+(dr-st)/2;
                  if(q==0)
                    {if(x==v[mid]) poz=mid;   //fprintf(stderr,"!\n"); fflush(stderr);
                     if(x<v[mid]) dr=mid-1;
                     else st=mid+1;  continue;
                    }
                  if(q==1)
                    {if(v[mid]<=x) poz=mid,st=mid+1;
                     else  dr=mid-1; continue ;
                    }
                  if(v[mid]>=x) poz=mid,dr=mid-1;
                  else st=mid+1; continue ;
                 }
            printf("%d\n",poz);
           }  free(v);
      //system("PAUSE>NULL");
      return 0;
  }