Cod sursa(job #2483959)

Utilizator alexnigaNiga Alexandru alexniga Data 30 octombrie 2019 16:25:06
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("cautbin.in");
ofstream g("cautbin.out");

int BinarySearchMaxEqual(int st, int dr, int x, vector <int>&v)
{
    int ans = -1;

    while (st <= dr)
    {
        int mij = (st + dr) / 2;
        if (v[mij] == x)
        {
            if (ans < mij)
                ans = mij;
        }
        if (v[mij] <= x)
        {
            st = mij + 1;
        }
        else
        {
            dr = mij - 1;
        }
    }

    return ans;

}

int BinarySearchMaxLowerOrEqual(int st, int dr, int x, vector <int>&v)
{
    int ans = -1;

    while (st <= dr)
    {
        int mij = (st + dr) / 2;

        if (v[mij] <= x)
        {
            ans = mij;
            st = mij + 1;
        }
        else
        {
            dr = mij - 1;
        }
    }

    return ans;

}

int BinarySearchMinLowerOrEqual(int st, int dr, int x, vector <int>&v)
{
    int ans = -1;

    while (st <= dr)
    {
        int mij = (st + dr) / 2;

        if (v[mij] >= x)
        {
            ans = mij;
            dr = mij - 1;
        }
        else
        {
            st = mij + 1;
        }
    }

    return ans;

}

int main()
{
    int n, m;

    f >> n;

    vector <int> v(n);

    for (int i = 0; i < n; i++)
        f >> v[i];

    f >> m;

    while(m--)
    {
        int test, x;

        f >> test >> x;

        if (test == 0)
        {
            int rez = BinarySearchMaxEqual(0, n - 1, x, v);
            if (rez == -1)
                g << -1 << "\n";
            else
                g << rez + 1 << "\n";
        }
        if (test == 1)
        {
            int rez = BinarySearchMaxLowerOrEqual(0, n - 1, x, v);
            if (rez == -1)
                g << -1 << "\n";
            else
                g << rez + 1 << "\n";
        }
        if (test == 2)
        {
            int rez = BinarySearchMinLowerOrEqual(0, n - 1, x, v);
            if (rez == -1)
                g << -1 << "\n";
            else
                g << rez + 1 << "\n";
        }
    }

    return 0;
}