Cod sursa(job #2238136)

Utilizator dragos192k1Dragos-Iulian Galeteanu dragos192k1 Data 4 septembrie 2018 18:05:37
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <cstdio>

using namespace std;

int n, m, v[100005], quest, x;

inline int solve_quest0(int x)
{
    int step, poz;

    for (step = 1; step <= n; step <<= 1);

    for (poz = 0; step; step >>= 1)
        if (poz + step <= n && v[poz + step] == x)
            poz += step;

    return poz;
}

inline int solve_quest1(int x)
{
    int step, poz;

    for (step = 1; step <= n; step <<= 1);

    for (poz = 0; step; step >>= 1)
        if (poz + step <= n && v[poz + step] <= x)
            poz += step;

    return poz;
}

inline int solve_quest2(int x)
{
    int step, poz;

    for (step = 1; step <= n; step <<= 1);

    for (poz = n; step; step >>= 1)
        if (poz - step >= 1 && v[poz - step] >= x)
            poz -= step;

    return poz;
}

int main()
{
    FILE *in, *out;
    in = freopen("cautbin.in", "r", stdin);
    out = freopen("cautbin.out", "w", stdout);

    scanf("%d", &n);

    for (int i = 1; i <= n; ++i) scanf("%d", &v[i]);

    scanf("%d", &m);

    for (int i = 1; i <= m; ++i) {
        scanf("%d%d", &quest, &x);
        if (!quest) printf("%d\n", solve_quest0(x));
        else if (quest == 1) printf("%d\n", solve_quest1(x));
             else printf("%d\n", solve_quest2(x));
    }

    fclose(in);
    fclose(out);
    return 0;
}