Cod sursa(job #2786855)

Utilizator qubitrubbitQubit Rubbit qubitrubbit Data 21 octombrie 2021 19:23:19
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;

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

int upperBound(int left, int right, int arr[], int val)
{
    int pos = -1;
    while (left <= right)
    {
        int mid = (left + right) / 2;
        if (arr[mid] <= val)
        {
            pos = mid;
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }
    return pos;
}

int lowerBound(int left, int right, int arr[], int val)
{
    int pos = -1;
    while (left <= right)
    {
        int mid = (left + right) / 2;
        if (arr[mid] >= val)
        {
            pos = mid;
            right = mid - 1;
        }
        else
        {
            left = mid + 1;
        }
    }
    return pos;
}

int main()
{
    int n, q, type, val;
    fin >> n;
    int arr[n];
    for (int i = 0; i < n; ++i)
    {
        fin >> arr[i];
    }
    fin >> q;
    while (q-- > 0)
    {
        fin >> type >> val;
        if (type == 0)
        {
            int pos = upperBound(0, n - 1, arr, val);
            if (arr[pos] != val)
            {
                pos = -2;
            }
            fout << pos + 1 << "\n";
        }
        else if (type == 1)
        {
            fout << upperBound(0, n - 1, arr, val) + 1 << "\n";
        }
        else if (type == 2)
        {
            fout << lowerBound(0, n - 1, arr, val) + 1 << "\n";
        }
    }
    return 0;
}