Cod sursa(job #650442)

Utilizator I.AlexandruIlie Alexandru I.Alexandru Data 18 decembrie 2011 03:05:12
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include<fstream>
#include<iostream>
#define maxn 100001
using namespace std;

int n, v[maxn], m, x, j, choice;
ifstream f("cautbin.in");
ofstream g("cautbin.out");

int cautare_binara(int v[], int value, int low, int high)
{int mid;
while(low<=high)
     {mid=low+(high-low)/2;
      if(value==v[mid])
        return mid;
      if(value<v[mid])
        high=mid-1;
      else low=mid+1; 
       }  
return -1;
}

int c0(int x)
{int poz=cautare_binara(v, x, 1, n);
while(v[poz+1]==x)
     poz++;
return poz;
}

int c1(int x)
{int poz=cautare_binara(v, x, 1, n);
while(v[poz+1]==x)
     poz++;
return poz;
}

int c2(int x)
{int poz=cautare_binara(v, x, 1, n);
while(v[poz-1]==x)
     poz--;
return poz;
}

int main()
{f>>n;
for(j=1; j<=n; j++)
   f>>v[j];    

f>>m;
for(j=1; j<=m; j++)
   {f>>choice;
    f>>x;
    switch(choice)
         {case 0: g<<c0(x)<<endl;
                  break;
          case 1: g<<c1(x)<<endl;
                  break;
          case 2: g<<c2(x)<<endl;
                  break;
         }
   }

f.close();
g.close();
//cout<<cautare_binara(v, 3, 1, n);
//system("pause");
return 0;
}