Cod sursa(job #3288507)

Utilizator tudor11Lungu Tudor tudor11 Data 22 martie 2025 15:59:20
Problema Cautare binara Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define M 100

int putere(int n)
{
  int p=1;
  while(p*2<n)
    p*=2;
  return p;
}

bool cond1(int index, int *v, int k, int n)
{
  return v[index]==k;
}
bool cond2(int index, int *v, int k, int n)
{
  return v[index]<=k;
}
bool cond3(int index, int *v, int k, int n)
{
  return v[index]>=k;
}

int main()
{
  int n,m,v[M];
  FILE *f,*F;
  if((f=fopen("cautbin.in","r"))==NULL)
    {
      perror(NULL);
      exit(-1);
    }
  if(fscanf(f,"%d",&n)!=1)
    {
      perror(NULL);
      fclose(f);
      exit(-1);
    }
  for(int i=0;i<n;i++)
    if(fscanf(f,"%d",v+i)!=1)
      {
	perror(NULL);
	fclose(f);
	exit(-1);
      }
  if(fscanf(f,"%d",&m)!=1)
    {
      perror(NULL);
      fclose(f);
      exit(-1);
    }
  if((F=fopen("cautbin.out","w"))==NULL)
    {
      perror(NULL);
      fclose(f);
      exit(-1);
    }
  for(int i=0;i<m;i++)
    {
      int c,x;
      if(fscanf(f,"%d %d",&c, &x)!=2)
	{
	  perror(NULL);
	  fclose(F);
	  fclose(f);
	  exit(-1);
	}
      if(c==0)
	{
	  int acc=0,cur_pow=putere(n);
	  while(cur_pow>0)
	    {
	      if(cond1(acc+cur_pow,v,x,n))
		acc+=cur_pow;
	      cur_pow>>=1;
	    }
	  if(acc!=0)
	    fprintf(F,"%d\n",acc+1);
	  else
	    fprintf(F,"-1\n");
	}
      else
	{
	  if(c==1)
	    {
	      int acc=0,cur_pow=putere(n);
	       while(cur_pow>0)
		 {
		   if(cond2(acc+cur_pow,v,x,n))
		     acc+=cur_pow;
		   cur_pow>>=1;
		 }
	       fprintf(F,"%d\n",acc+1);
	    }
	  else
	    {
	      int acc=-1,cur_pow=1;
	      while(cur_pow<putere(n))
		 {
		   if(cond3(acc+cur_pow,v,x,n))
		     acc+=cur_pow;
		   cur_pow<<=1;
		 }
	      fprintf(F,"%d\n",acc+1);
	    }
	}
    }
  fclose(f);
  fclose(F);
  return 0;
}