Cod sursa(job #2239226)

Utilizator NewGloryMihnea Andreescu NewGlory Data 10 septembrie 2018 10:37:52
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    freopen("cautbin.in","r",stdin);
    freopen("cautbin.out","w",stdout);
    int n;
    cin>>n;
    vector<int>v(n);
    for(int i=0;i<n;i++)
        cin>>v[i];
    int q;
    cin>>q;
    while(q--)
    {
        int t,x;
        cin>>t>>x;
        if(t==0)
        {
            int lo=0;
            int hi=n-1;
            int ans=-1;
            while(lo<=hi)
            {
                int med=(lo+hi)/2;
                if(x==v[med])
                    ans=med+1;
                if(x>=v[med])
                    lo=med+1;
                else
                    hi=med-1;
            }
            cout<<ans<<"\n";
        }
        if(t==1)
        {
            int lo=0;
            int hi=n-1;
            int ans=-1;
            while(lo<=hi)
            {
                int med=(lo+hi)/2;
                if(v[med]<=x)
                {
                    ans=med+1;
                    lo=med+1;
                }
                else
                    hi=med-1;
            }
            cout<<ans<<"\n";
        }
        if(t==2)
        {
            int lo=0;
            int hi=n-1;
            int ans=-1;
            while(lo<=hi)
            {
                int med=(lo+hi)/2;
                if(v[med]>=x)
                {
                    ans=med+1;
                    hi=med-1;
                }
                else
                    lo=med+1;
            }
            cout<<ans<<"\n";
        }
    }
    return 0;
}