Cod sursa(job #2368548)

Utilizator RussianSmoothCriminalRodion Raskolnikov RussianSmoothCriminal Data 5 martie 2019 16:33:31
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>

using namespace std;

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

int a[100005], n, m;

int BinSearch0 (int x)
{
    int left, right, mid, pos = -1;
    left = 1;
    right = n;
    while (left <= right)
    {
        mid = (left + right) / 2;
        if (a[mid] == x)
        {
            pos = mid;
            left = mid + 1;
        }
        else if (a[mid] < x)
            left = mid + 1;
        else right = mid - 1;
    }
    return pos;
}

int BinSearch1 (int x)
{
    int left, right, mid, pos = -1;
    left = 1;
    right = n;
    while (left <= right)
    {
        mid = (left + right) / 2;
        if (a[mid] <= x)
        {
            pos = mid;
            left = mid + 1;
        }
        else right = mid - 1;
    }
    return pos;
}

int BinSearch2 (int x)
{
    int left, right, mid, pos = -1;
    left = 1;
    right = n;
    while (left <= right)
    {
        mid = (left + right) / 2;
        if (a[mid] >= x)
        {
            pos = mid;
            right = mid - 1;
        }
        else left = mid + 1;
    }
    return pos;
}

void Solve ()
{
    int i, op, x;
    fin >> n;
    for (i = 1; i <= n; i++)
        fin >> a[i];
    fin >> m;
    for (i = 1; i <= m; i++)
    {
        fin >> op >> x;
        if (!op) fout << BinSearch0(x) << "\n";
        else if (op == 1) fout << BinSearch1(x) << "\n";
        else fout << BinSearch2(x) << "\n";
    }
    fout.close();
}

int main()
{
    Solve();
    return 0;
}