Cod sursa(job #2620624)

Utilizator alezgandruOana Alexandru Andrei alezgandru Data 29 mai 2020 12:29:53
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in ("cautbin.in");
ofstream out ("cautbin.out");

int main()
{
    int v[100001];
    int n;
    in >> n;

    for (int i = 1; i <= n; i ++)
    {
        in >> v[i];
    }
     int m;
     in >> m;

     for (int j = 1; j <= m; j++)
     {
         int q, x, st = 1, dr = n , m;
         in >> q;
         in >> x;

         while (st <= dr)
         {
             m = (st + dr) / 2;
             if ( v[m] < x )
                 st = m + 1;
             else dr = m - 1;
         }

         if(q == 0)
         {
             if (v[st] != x) out << -1 <<endl;
             else
             {
                 int index = st;
             while (v[index + 1] == v[st])
             {
                 index += 1 ;
             }
             out << index << endl;
             }
         }
         else if (q == 1)
         {
             int ind = st + 1;
             while(v[ind] <= v[st])
             {
                 ind ++;
             }
             out << ind - 1 << endl;
         }
         else if (q == 2)
         {
             out << st << endl;
         }
     }

    return 0;
}