Cod sursa(job #2941899)

Utilizator RaduAlexandruTimoteiRadu Alexandru Timotei RaduAlexandruTimotei Data 18 noiembrie 2022 15:32:15
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>

using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int n,m,x,c,st,dr,poz,z;
int main()
{
    f>>n;
    int v[n+2];
    for(int i=1;i<=n;i++) f>>v[i];
    f>>z;
    for(int i=1;i<=z;i++)
    {
       f>>c>>x;
       if(c==0)
       {
          st=1;
          dr=n;
          poz=0;
          while(st<=dr && poz==0)
          {
             m=(st+dr)/2;
             if(v[m]==x) poz=m;
             else if(v[m]<x) st=m+1;
             else dr=m-1;
          }
          while(v[poz+1]==x && poz<=n) poz++;
          if(poz==0) g<<-1;
          else g<<poz;
       }
       if(c==1)
       {
          st=1;
          dr=n;
          poz=0;
          while(st<=dr)
          {
             m=(st+dr)/2;
             if(v[m]<=x)
             {
                poz=m;
                st=m+1;
             }
             else dr=m-1;
          }
          g<<poz;
       }
       if(c==2)
       {
          st=1;
          dr=n;
          poz=0;
          while(st<=dr)
          {
             m=(st+dr)/2;
             if(v[m]>=x)
             {
                poz=m;
                dr=m-1;
             }
             else st=m+1;
          }
          g<<poz;
       }
       g<<'\n';
    }
    return 0;
}