Cod sursa(job #2679130)

Utilizator sstanciu10Stanciu Sergiu Nicolas sstanciu10 Data 29 noiembrie 2020 17:52:04
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream f("cautbin.in");
ofstream g("cautbin.out");
int N, A[100], i;

int binary_search(int val, int step)
{
    int i;
    for (i = 0; step; step >>= 1)
        if (i + step < N && A[i + step] <= val)
           i += step;
    return i;
}
int lg, logN;
int aux;
int M, tip ,x;
int aux_;
int main()
{
    f>>N;
    for(i=1; i<=N; ++i)
        f>>A[i];
    for(logN = 1 ; logN<=N; logN<<=1);
    f>>M;
    for( ; M; --M)
    {
        f>>tip>>x;
        if(tip<2)
        {
            aux = binary_search(x, logN);
            if(!tip and !aux)
                g<<"-1"<<endl;
            if(!tip and aux!=0) g<<aux<<endl;
            if(tip==1 and aux) g<<aux<<endl;
            if(tip==1 and aux==0)   {
                while(aux_)
            {
                aux_= binary_search(x, logN);
                --x;
            }
            g<<aux_<<endl;
            }

            continue;
        }
        else
        for (lg = logN, i = N; lg; lg >>= 1)
            if (i - lg > 0 && A[i - lg] >= x)
                i -= lg;
        g<<i<<endl;
    }
    return 0;
}