Cod sursa(job #1649112)

Utilizator serbanSlincu Serban serban Data 11 martie 2016 12:36:17
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <algorithm>

using namespace std;

int n;
int a[100005];

int main()
{
    ifstream f("cautbin.in");
    ofstream g("cautbin.out");
    f >> n;
    for(int i = 1; i <= n; i ++) f >> a[i];
    sort(a + 1, a + n + 1);
    int m, op, x; f >> m;
    int l, r;
    for(; m; m --) {
        f >> op >> x;
        if(op == 0) {
            int step = 1;
            for(; step <= n; step <<= 1);
            int i = 1;
            for(i = 1; step; step >>= 1) {
                if(i + step <= n && a[i + step] <= x)
                    i += step;
            }
            if(a[i] == x) g << i << "\n";
            else g << "-1\n";
        }
        else if(op == 1) {
            int i, step = 1;
            for(; step <= n; step <<= 1);
            for(i = 1; step; step >>= 1)
                if(i + step <= n && a[i + step] <= x)
                    i += step;
            g << i << "\n";
        }
        else if(op == 2) {
            x --;
            int i, step = 1;
            for(; step <= n; step <<= 1);
            for(i = 1; step; step >>= 1)
                if(i + step <= n && a[i + step] <= x)
                    i += step;
            g << i << "\n";
        }
    }
    return 0;
}