Cod sursa(job #3214897)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 14 martie 2024 15:39:35
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

const int max_size = 1e5 + 20, rmax = 20;

int v[max_size], n;

int cb12 (int val)
{
    int st = 0, e = 20;
    while (e >= 0)
    {
        if (st + (1 << e) <= n && v[st + (1 << e)] <= val)
        {
            st += (1 << e);
        }
        e--;
    }
    return st;
}

int cb3 (int val)
{
    int dr = n, e = 20;
    while (e >= 0)
    {
        if (dr - (1 << e) > 0 && v[dr - (1 << e)] >= val)
        {
            dr -= (1 << e);
        }
        e--;
    }
    return dr;
}

void solve ()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> v[i];
    }
    int q;
    cin >> q;
    while (q--)
    {
        int op, x;
        cin >> op >> x;
        if (op == 0)
        {
            int y = cb12(x);
            if (v[y] != x)
            {
                cout << -1;
            }
            else
            {
                cout << y;
            }
        }
        if (op == 1)
        {
            cout << cb12(x);
        }
        if (op == 2)
        {
            cout << cb3(x);
        }
        cout << '\n';
    }
    cout << '\n';
}

signed main ()
{
#ifdef LOCAL
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#else
    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);
#endif // LOCAL
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    long long tt;
    //cin >> tt;
    tt = 1;
    while (tt--)
    {
        solve();
    }
    return 0;
}