Cod sursa(job #3138350)

Utilizator alex210046Bratu Alexandru alex210046 Data 19 iunie 2023 07:44:43
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int v[100000], n;

int cautBin1(int x)
{
    int p = 0, u = n - 1, poz = -1;
    while(p <= u)
    {
        int m = (p + u) / 2;
        if(v[m] == x)
        {
            poz = m;
            p = m + 1;
        }
        else
        if(x > v[m])
            p = m + 1;
        else
            u = m - 1;
    }

    if(poz < 0) return -1;
    else return poz + 1;
}

int cautBin2(int x)
{
    int p = 0, u = n - 1, poz = -1;
    while(p <= u)
    {
        int m = (p + u) / 2;
        if(v[m] <= x)
        {
            poz = m;
            p = m + 1;
        }
        else
        if(x > v[m])
            p = m + 1;
        else
            u = m - 1;
    }

    return poz;
}

int cautBin3(int x)
{
    int p = 0, u = n - 1, poz = -1;
    while(p <= u)
    {
        int m = (p + u) / 2;
        if(x <= v[m])
        {
            poz = m;
            u = m - 1;
        }
        else
        if(x > v[m])
            p = m + 1;
        else
            u = m - 1;
    }
    return poz;
}

int main() {
    f >> n;
    for(int i = 0; i < n; i++)
        f >> v[i];
    int m, x, y; f >> m;
    while (m --) {
        f >> x >> y;
        if(x == 0)
            g << cautBin1(y) << '\n';
        else if(x == 1)
            g << cautBin2(y) + 1 << '\n';
        else if(x == 2)
            g << cautBin3(y) + 1 << '\n';
    }

    return 0;
}