Cod sursa(job #2651309)

Utilizator alexia208160Popescu Alexia Maria alexia208160 Data 22 septembrie 2020 10:32:38
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

int cb(int v[], int n, int x)
{
    int ls = 0,ld = n - 1,mij;
    while (ls <= ld)
    {
        mij = (ls + ld) / 2;
        if (v[mij] == x) return mij;
        if (v[mij] < x) ls = mij + 1;
        else ld = mij - 1;
    }
    return -1;
}

int cb1(int v[], int n, int x)
{
    int ls = 0,ld = n - 1,mij;
    while (ls <= ld)
    {
        mij = (ls + ld) / 2;
        if (v[mij] == x) return mij;
        if (v[mij] < x) ls = mij + 1;
        else ld = mij - 1;
    }
    return ld;
}

int cb2(int v[], int n, int x)
{
    int ls = 0,ld = n - 1,mij;
    while (ls <= ld)
    {
        mij = (ls + ld) / 2;
        if (v[mij] == x) return mij;
        if (v[mij] < x) ls = mij + 1;
        else ld = mij - 1;
    }
    return ls;
}

int main(void)
{
    int n,v[100000], a, b, m;
    fin >> n;
    for (int i = 0; i < n; i++)
        fin >> v[i];
    sort(v, v + n);
    fin >> m;
    for (int i = 0; i < m; i++)
    {
        fin >> a >> b;

        if (a == 0)
        {
            int p = cb(v, n, b);
            if (p != -1)
            {
                while (v[p] == v[p + 1])
                    p++;
                fout << p + 1 <<'\n';
            }
            else
                fout << -1 <<'\n';

        }
        if (a == 1)
        {
            int p = cb1(v, n, b);
            if (v[p] == b)
                while (v[p] == v[p + 1])
                    p++;
            fout << p + 1 <<'\n';
        }
        if (a == 2)
        {
            int p = cb2(v, n, b);
            if (v[p] == b)
                while (v[p] == v[p - 1])
                    p--;
            fout << p + 1 <<'\n';
        }
    }
    return 0;
}