Cod sursa(job #795643)

Utilizator luckyme91wiz kid luckyme91 Data 9 octombrie 2012 02:58:35
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <fstream>
#include <algorithm>

using namespace std;
int x[100001];
int begin, end, n, mid;
bool ok;
//ofstream out ("cautbin.out", ofstream::out);


int solve2 (int y, int s) {

    begin = 0;
    end = n;
    while (begin < end) {
        mid = begin + (end - begin)/2;
        if (x[mid] < s) {
            begin = mid + 1;
        }
        else {
            end = mid;
        }
    }

    if (x[end] < s)
        end++;
    
    return end + 1;
}

int solve1 (int y, int s) {

    begin = 0;
    end = n;
    while (begin < end) {
        mid = begin + (end - begin)/2;
        if (x[mid] <= s) {
            begin = mid + 1;
        }
        else {
            end = mid;
        }
    }

    if (x[end] > s)
        end--;
    if (end == n)
        end--;
    return end + 1;
}

int solve0 (int y, int s) {

    begin = 0;
    end = n;
    while (begin < end) {
        mid = begin + (end - begin)/2;
        if (x[mid] <= s) {
            begin = mid + 1;
        }
        else {
            end = mid;
        }
    }

    if (x[end] != s && x[end-1] != s)
        return -1;
    if (x[end - 1] == s)
        end--;

       return end + 1;
}

int main () {
    int q, y, s;
//    ifstream in ("cautbin.in", ifstream::in);
    freopen ("cautbin.in", "r", stdin);
    freopen ("cautbin.out", "w", stdout);


//    in >> n;
    scanf("%d", &n);

    for (int i = 1; i <= n; i++)
    {
//      in >> x[i];
        scanf("%d", &x[i]);
    }
    scanf("%d", &q);
//    in >> q;

    sort(x + 1, x + n + 1);
    while (q--)
    {
        //in >> y >> s;
        scanf ("%d %d", &y, &s);
        if (y == 0) {
            int res = upper_bound(x+1,x + n +1 , s) -x-1;
            if (res <= n && res >= 1 && x[res] == s)
                printf ("%d\n", /*solve0 (y, s)*/res );
            else printf("-1\n");
        }
        else if (y == 1)
           printf ("%d\n", /*solve1 (y, s)*/lower_bound(x + 1, x + n + 1, s + 1 ) - x - 1);
        else 
           printf ("%d\n", /*solve2 (y, s)*/upper_bound(x + 1, x + n + 1, s - 1 ) - x);
;
    }
}