Cod sursa(job #2659318)

Utilizator bem.andreiIceman bem.andrei Data 16 octombrie 2020 16:10:26
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>

using namespace std;
int v[100001];
ifstream r("cautbin.in");
ofstream w("cautbin.out");
int main()
{
    int n, m, a, x;
    r>>n;
    for(int i=0; i<n; i++)
    {
        r>>v[i];
    }
    r>>m;
    for(int j=0; j<m; j++)
    {
        r>>a>>x;
        if(a==0 || a==1)
        {
            int pos = -1, step = 1;


            while (step * 2 <= n)
                step *= 2;

            while (step > 0)
            {
                if (pos + step < n && v[pos + step] <= x)
                    pos += step;
                step /= 2;
            }
            if(a==0 && v[pos]!=x)
            {
                w<<"-1"<<"\n";
            }
            else
            {
                w<<pos+1<<"\n";
            }

        }
        else
        {
            int pos = -1, step = 1;


            while (step * 2 <= n)
                step *= 2;

            while (step > 0)
            {
                if (pos + step < n && v[pos + step] <= x-1)
                    pos += step;
                step /= 2;
            }
            w<<pos+2<<"\n";
        }
    }
    return 0;
}