Cod sursa(job #2566337)

Utilizator NotTheBatmanBruce Wayne NotTheBatman Data 2 martie 2020 20:37:29
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <iostream>
#include <stack>

using namespace std;

const int N = 1e5 + 5;

int a[N], n;

int BinSearch0 (int x)
{
    int left, right, mid, pos;
    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)
            right = mid - 1;
        else left = mid + 1;
    }
    return pos;
}

int BinSearch1 (int x)
{
    int left, right, mid, pos;
    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;
    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 Read ()
{
    ifstream fin ("cautbin.in");
    ofstream fout ("cautbin.out");
    fin >> n;
    for (int i = 1; i <= n; i++)
        fin >> a[i];
    int q;
    fin >> q;
    while (q--)
    {
        int op, x;
        fin >> op >> x;
        if (!op) fout << BinSearch0(x) << "\n";
        else if (op == 1) fout << BinSearch1(x) << "\n";
        else fout << BinSearch2(x) << "\n";
    }
    fout.close();
    fin.close();
}



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