Cod sursa(job #1302207)

Utilizator lolmanDomuta Dariu lolman Data 26 decembrie 2014 18:30:46
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
using namespace std;
int x,n,mid,v[100001],i,y,m,quest,j;
int position(int x)
  {
      int ok=0;
      for (i=n;i>=1;i--)
             if (v[i]==x)
                 {
                    ok=1;
                    return i;
                 }
      if(ok==0) return -1;
  }
int cautarebinara(int lo, int hi, int x)
            {
                int mid=lo+(hi-lo)/2;
                if (v[mid]==x) return position(x);
                            else if (x<v[mid]) return cautarebinara (1, mid,x);
                                            else return cautarebinara (mid+1, hi,x);

            }
int main()
{
    ifstream f("cautbin.in");
    ofstream g("cautbin.out");
    f>>n;
    for (i=1;i<=n;i++) f>>v[i];
    f>>m;
    for (j=1;j<=m;j++)
          {
              f>>quest;
              f>>x;
              y=cautarebinara(1,n,x);
              if (quest==0) g<<y<<'\n';
              if (quest==1)
                  {
                      if (y!=-1) g<<y<<'\n';
                                else for (i=1;i<=n;i++) if(v[i]>x) {g<<i-1<<'\n'; break;}
                  }
              if (quest==2)
                  {
                      for (i=1;i<=n;i++) if(v[i]>=x) {g<<i<<'\n'; break;}
                  }
          }
    return 0;
}