Cod sursa(job #3165216)

Utilizator nicushor21Pirlog Marian Nicolae nicushor21 Data 5 noiembrie 2023 17:51:27
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;
int n,m,p,i,j,v[100000],mid,st,dr,x,poz;
int main(){  
    ifstream fin("cautbin.in");
    ofstream fout("cautbin.out");
    fin>>n;
    for(i=0;i<n;i++){
        fin>>v[i];
    }
    fin>>m;
    for(i=0;i<m;i++){
        fin>>p>>x;
        if(p==0){
            st=0; dr=n-1; poz=-1;
            while(st<=dr){
                mid=(st+dr)/2;
                if(x==v[mid]){
                    poz=mid;
                    st=mid+1;
                }else{
                    if(x<v[mid]){
                        dr=mid-1;
                    }else{
                        st=mid+1;
                    }
                }
            }
            fout<<poz+1<<'\n';
        }else if(p==1){
            st=0; dr=n-1; poz=-1;
            while(st<=dr){
                mid=(st+dr)/2;
                if(x<v[mid]){
                    dr=mid-1;
                }else{
                    st=mid+1;
                    poz=mid;
                }
            }
            fout<<poz+1<<'\n';
        }else{
            st=0; dr=n-1; poz=-1;
            while(st<=dr){
                mid=(st+dr)/2;
                if(x<=v[mid]){
                    dr=mid-1;
                    poz=mid;
                }else{
                    st=mid+1;
                }
            }
            fout<<poz+1<<'\n';
        }
    }
    return 0;
}