Cod sursa(job #1679087)

Utilizator NicholasFlamelFasie Vlad George NicholasFlamel Data 7 aprilie 2016 17:57:18
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>

using namespace std;

int v[100];

int cautbin(int low, int up, int op, int val) {
    //cout << endl << low << " " << up;
    if ( low > up ) {
        return -1;
    }
    int mid = (low + up) / 2;
    int pos;
    switch (op) {
        case 0:
            if ( v[mid] == val ) {
                for ( pos = mid; v[pos] == val && pos <= up; ++pos );
                return pos;
            } else {
                break;
            }
        case 1: {
            if ( v[mid] <= val ) {
                for ( pos = mid; v[pos] <= val && pos <= up; ++pos ) ;
                return pos;
            } else {
                break;
            }
        }
        case 2: {
            if ( v[mid] >= val ) {
                for ( pos = mid; v[pos] >= val && pos >= up; --pos ) ;
                return pos;
            } else {
                break;
            }
        }
    }
    if ( val < v[mid] ) {
        return cautbin(low, mid-1, op, val);
    } else {
        return cautbin(mid + 1, up, op, val);
    }
}

int main()
{
    int n, m, op, val;
    ifstream in;
    ofstream out;
    in.open("cautbin.in");
    out.open("cautbin.out");
    in >> n;
    for ( int i = 0; i < n; ++i ) {
        in >> v[i];
    }
    in >> m;
    for (int i = 0; i < m; ++i ) {
        in >> op >> val;
        out << cautbin(0, n-1, op, val) << "\n";
    }
    in.close();
    out.close();
    return 0;
}