Cod sursa(job #2214743)

Utilizator AndreiDumitrescuAndrei Dumitrescu AndreiDumitrescu Data 19 iunie 2018 23:13:32
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f("cautbin.in");
ofstream g("cautbin.out");

int v[100010];

int caut_binar(int val, int n){
    int pos=0;
    for(int bit = 20; bit >= 0; bit--)
        if((pos +( 1 << bit) <=n) && (v[pos +(1 << bit)] <= val))
            pos+=(1 << bit);
    return pos;
}

int main()
{
    int n, m, tip, x;
    f >> n;
    for(int i = 1; i <= n; i++)
        f >> v[i];
    f >> m;
    for(int i = 1; i <= m; i++)
    {
        f >> tip >> x;
        if(tip == 0)
        {
            poz = caut_binar(x, n);
            if(v[poz] == x)
                g << poz << '\n';
            else
                g << "-1" << '\n';
        }
        if(tip == 1)
            g << caut_binar(x, n) << '\n';
        if
            g << caut_binar(x - 1, n) + 1 << '\n';

    }
    return 0;
}