Cod sursa(job #2954895)

Utilizator Pop_EmilPal Tamas Pop_Emil Data 15 decembrie 2022 19:09:00
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>

using namespace std;

FILE *in = fopen("cautbin.in", "r"), *out = fopen("cautbin.out", "w");
int N, M;
int arr[100005];

int cautbin(int x)
{
    int h = N, l = 1, m;
    while(l <= h)
    {
        m = l + (h-l)/2;

        if (x < arr[m])
            h = m - 1;
        else if (x > arr[m])
            l = m + 1;
        else {
            while (x == arr[m + 1] && m <= N)
                m += 1;
            return m;
        }
    }
    return h;
}

int cautbin2(int x)
{
    int h = N, l = 1, m;
    while(l <= h)
    {
        m = l + (h-l)/2;

        if (x < arr[m])
            h = m - 1;
        else if (x > arr[m])
            l = m + 1;
        else {
            while (x == arr[m - 1] && m >= 1)
                m -= 1;
            return m;
        }
    }
    return l;
}


int main()
{
    fscanf(in, "%d", &N);
    for (int i = 1; i <= N; ++i)
        fscanf(in, "%d", &arr[i]);

    fscanf(in, "%d", &M);
    int type, x, res;
    for (int i = 1; i <= M; ++i)
    {
        fscanf(in, "%d %d", &type, &x);
        if (type == 0)
        {
            res = cautbin(x);
            if (arr[res] != x)
                res = -1;
        }
        else if (type == 1)
            res = cautbin(x);
        else if (type == 2)
            res = cautbin2(x);

        fprintf(out, "%d\n", res);
    }

    return 0;
}