Cod sursa(job #2754178)

Utilizator RedPipperNastasa Stefan-Alexandru RedPipper Data 25 mai 2021 12:46:41
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <fstream>
#include <iostream>

using namespace std;
ifstream fin("cautbin.in");

int n, v[100000];

int cautbin(int x){

    int left = 0;
    int right = n;

    while(left<right){
        int mid = (left+right)/2;
        if(x<v[mid])
        {
            right = mid-1;
        }
        else if(x>v[mid])
        {
            left = mid+1;
        }
        else{
            return mid;
        }

    }

    return -1;

}

int main(){
    fin>>n;
    for(int i=0;i<n;++i)
        fin>>v[i];

    int t;
    fin>>t;
    while(t--){
        int op, nr;
        fin>>op>>nr;
        int pos = cautbin(nr);
        if(op == 0){
            if(pos == -1)
                cout<<-1<<'\n';
            else{
                while(v[pos] == nr)++pos;
                cout<<pos<<'\n';
            }
        }
        else if( op == 1){
            int i=0;
            while(v[i]<=nr)++i;
            cout<<i<<'\n';
        }
        else if( op == 2){
            int i=n-1;
            while(v[i]>=nr)--i;
            cout<<i+2<<'\n';
        }
    }


    return 0;
}