Cod sursa(job #330739)

Utilizator Bogdan_CCebere Bogdan Bogdan_C Data 11 iulie 2009 13:40:55
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include<fstream>

using namespace std;
int n,m,x,a[10000],s,poz,gasit,dist;
void cautexact(int in,int sf,int &poz1)
{
    if (in<sf)
     {int mij=in+(sf-in)/2;
      if(a[mij]==x) {poz1=mij;}
      else if(x>a[mij]) {cautexact(mij+1,sf,poz1);}
           else cautexact(in,mij,poz1);      }
      
    }
void cautmic(int in, int sf,int &poz1)
{
if(in<sf)
 {int mij=in+(sf-in)/2;
 if( (x-a[mij])<dist && (x-a[mij])>0) {poz1=mij;dist=x-a[mij];}
 if ((x-a[mij])>0) cautmic(mij+1,sf,poz1);
  else cautmic(in,mij,poz1);          
         
         }
    
    
    }
void cautmare(int in,int sf,int &poz1)
{
if(in<sf)
 {int mij=in+(sf-in)/2;
 if( (a[mij]-x)<dist && (a[mij]-x)>0) {poz1=mij;dist=a[mij]-x;}
 if ((a[mij]-x)>0) cautmare(in,mij,poz1);
  else cautmare(mij+1,sf,poz1);          
         
         }
    
    
    }
int main()
{ifstream in("cautbin.in");
ofstream out("cautbin.out");
in>>n;
for(int i=1;i<=n;i++)
 in>>a[i];
in>>m;
//mergesort(1,n);
for(;m;m--)
 {in>>s>>x;
  if(s==0) {cautexact(1,n,poz);out<<poz<<'\n';}
  else if(s==1) {poz=1;dist=x-a[1];cautmic(1,n,poz);out<<poz<<'\n';}
       else {poz=n;dist=a[n]-x;cautmare(1,n,poz);out<<poz<<'\n';}
           
           
           } 
 
 return 0;
 }