Cod sursa(job #987710)

Utilizator manutrutaEmanuel Truta manutruta Data 21 august 2013 13:28:42
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
# include <iostream>
# include <fstream>
using namespace std;

# define INF 0x3f3f3f3f
# define MAXN 100010

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

int n;
int a[MAXN];

int search1(int x) {
    int st = 1, dr = n;
    while (st <= dr) {
        int mid = st + ((dr - st) >> 1);
        if (a[mid] == x && a[mid + 1] > x) {
            return mid;
        }
        if (a[mid] <= x) {
            st = mid + 1;
        } else {
            dr = mid - 1;
        }
    }
    return -1;
}

int search2(int x) {
    int st = 1, dr = n;
    while (st <= dr) {
        int mid = st + ((dr - st) >> 1);
        if (a[mid] <= x && a[mid + 1] > x) {
            return mid;
        }
        if (a[mid] <= x) {
            st = mid + 1;
        } else {
            dr = mid - 1;
        }
    }
}

int search3(int x) {
    int st = 1, dr = n;
    while (st <= dr) {
        int mid = st + ((dr - st) >> 1);
        if (a[mid] >= x && a[mid - 1] < x) {
            return mid;
        }
        if (a[mid] >= x) {
            dr = mid - 1;
        } else {
            st = mid + 1;
        }
    }
}

int main()
{
    f >> n;
    for (int i = 1; i <= n; i++) {
        f >> a[i];
    }
    a[n + 1] = INF;
    a[0] = -1;

    int q;
    f >> q;
    for (int i = 1; i <= q; i++) {
        int op, x;
        f >> op >> x;
        switch (op) {
            case 0:
                g << search1(x) << '\n';
                break;
            case 1:
                g << search2(x) << '\n';
                break;
            case 2:
                g << search3(x) << '\n';
                break;
        }
    }

    return 0;
}