Cod sursa(job #3307055)

Utilizator robigiirimias robert robigi Data 16 august 2025 19:24:26
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#include <vector>

using namespace std;

int rightmostExactBS(const vector<int>& v, int x)
{
    int low = 1;
    int high = (int)v.size() - 1;
    while (low <= high)
    {
        int mid = (low + high) / 2;
        if (x >= v[mid])
            low = mid + 1;
        else high = mid - 1;
    }
    if (v[high] == x)
        return high;
    return -1;
}

int rightmostLessThanBS(const vector<int>& v, int x)
{
    int low = 1;
    int high = (int)v.size() - 1;
    while (low <= high)
    {
        int mid = (low + high) / 2;
        if (x >= v[mid])
            low = mid + 1;
        else high = mid - 1;
    }
    if (v[high] <= x)
        return high;
    return -1;
}

int leftmostGreaterThanBS(const vector<int>& v, int x)
{
    int low = 1;
    int high = (int)v.size() - 1;
    while (low <= high)
    {
        int mid = (low + high) / 2;
        if (x > v[mid])
            low = mid + 1;
        else high = mid - 1;
    }
    if (v[low] >= x)
        return low;
    return -1;
}

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

    int n, m;
    fin >> n;

    vector<int>v(n + 1);

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

    fin >> m;
    for (int i = 1; i <= m; ++i)
    {
        int task, x;
        fin >> task >> x;
        if (task == 0)
        {
            fout << rightmostExactBS(v, x) << "\n";
        }
        else if (task == 1)
        {
            fout << rightmostLessThanBS(v, x) << "\n";
        }
        else if (task == 2)
        {
            fout << leftmostGreaterThanBS(v, x) << "\n";
        }
    }

    return 0;
}