Cod sursa(job #3148679)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 3 septembrie 2023 13:11:11
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
using namespace std;
using pii = pair<int,int>;
ifstream cin("cautbin.in");
ofstream cout("cautbin.out");
const int MAX = 1e5 + 1;
int n , v[MAX] , q , t , x , pw , ogpw;
signed main()
{
    ogpw = 1;
    cin >> n;
    while(true)
    {
        if(ogpw*2<=n) ogpw*=2;
        else break;
    }
    for(int i = 1 ; i <= n ; i++) cin >> v[i];
    cin >> q;
    while(q--)
    {
        cin >> t >> x;
        if(t<2)
        {
            pw = ogpw;
            int ans = 0;
            while(true)
            {
                if(ans+pw<=n&&v[ans+pw]<=x)
                {
                    ans+=pw;
                }
                if(pw==1) break;
                pw >>= 1;
            }
            if(!t)
            {
                if(v[ans]==x) cout << ans;
                else cout << -1;
            }
            else cout << ans;
        }
        else
        {
            pw = ogpw;
            int ans = 0;
            while(true)
            {
                if(ans+pw<=n&&v[ans+pw]<x)
                {
                    ans+=pw;
                }
                if(pw==1) break;
                pw >>= 1;
            }
            cout << ans + 1;
        }
        cout << '\n';
    }
    return 0;
}