Cod sursa(job #649979)

Utilizator I.AlexandruIlie Alexandru I.Alexandru Data 17 decembrie 2011 02:31:19
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include<fstream>
#include<iostream>
#define maxn 100001
using namespace std;

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

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

int c0(int x)
{int poz=cautare_binara(v, x, 1, n);
while(v[poz+1]==x)
     poz=cautare_binara(v, x, poz, n);
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();
return 0;
}