Cod sursa(job #1455083)

Utilizator CollermanAndrei Amariei Collerman Data 27 iunie 2015 13:16:55
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <algorithm>
using namespace std;
ofstream fout("cautbin.out");
ifstream fin("cautbin.in");
const int NMAX = 100001;

int n, m, x, op, poz;
int v[NMAX];

void citire()
{
    fin >> n;
    for(int i=1; i<=n; i++) fin >> v[i];
    fin >> m;
}

void cautare()
{
    for(int i=1; i<=m; i++)
    {
        fin >> op >> x;

        if(!op) {
            poz = upper_bound(v + 1, v + n + 1, x) - v - 1;
            if(poz >= 1 && poz <= n && v[poz] == x) fout << poz << '\n';
            else fout << -1 << '\n';
        }
        else if(op == 1) {
            poz = lower_bound(v + 1, v + n + 1, x + 1) - v - 1;
            fout << poz << '\n';
        }
        else {
            poz = upper_bound(v + 1, v + n + 1, x - 1) - v;
            fout << poz << '\n';
        }
    }
}

int main()
{
    citire();
    cautare();

    fin.close();
    fout.close();
    return 0;
}