Cod sursa(job #1658440)

Utilizator CraiuAndrei Craiu Craiu Data 21 martie 2016 15:18:00
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
#include <algorithm>

using namespace std;

int a[100003], n;

int main ()
{
    int m, x, y, i, t;

    ifstream fin("cautbin.in");
    ofstream fout("cautbin.out");

    fin >> n;
    for (i = 1; i <= n; ++ i)
        fin >> a[i];

    sort(a + 1, a + n + 1);

    fin >> m;

    for (i = 1; i <= m; ++ i)
    {
        fin >> t >> y;
        if (t == 0)
        {
            x = upper_bound(a + 1, a + n + 1, y) - a - 1;
            if (x <= n && x >= 1 && a[x] == y)
                fout << x << "\n";
            else
                fout << "-1\n";
        }
        else if (t == 1)
        {
            x = lower_bound(a + 1, a + n + 1, y + 1) - a - 1;
            fout << x << "\n";
        }
        else
        {
            x = upper_bound(a + 1, a + n + 1, y - 1) - a;
            fout << x << "\n";
        }
    }
    fin.close();
    fout.close();
}