Cod sursa(job #3349907)

Utilizator Alberates10Albert Mates Alberates10 Data 3 aprilie 2026 13:39:05
Problema Cautare binara Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.5 kb
#include <iostream>
#include <map>
#include <vector>
#include <fstream>
using namespace std;

int main()
{
    int st,dr,c,x,n;
    ifstream fin("cautbin.in");
    ofstream fout("cautbin.out");
    fin>>n;
    vector<int>v(n);
    for(int i=0;i<n;i++){
        fin>>v[i];
    }
    int q;
    fin>>q;
    for(int i=0;i<q;i++){
        fin>>c>>x;
        if(c==0){
            st=0;
            dr=n;
            int rez=-2;
            /**if(v[n-1]==x){
                fout<<n;
            }
            else{**/
            while(st<=dr){
                int mij=st+((dr-st)/2);
                if(v[mij]<x){
                    st=mij+1;
                }
                if(v[mij]==x){
                    rez=mij;
                    st=mij+1;
                }
                if(v[mij]>x){
                    dr=mij-1;
                }
            }
            if(rez==-2){
                fout<<"-1"<<endl;
            }
            else{
                fout<<rez+1<<endl;
            }
            //}
        }
        if(c==1){
            st=0;
            dr=n;
            int rez=-2;
            if(v[n-1]==x){
                fout<<n;
            }
            else{
            while(st<=dr){
                int mij=st+((dr-st)/2);
                if(v[mij]<x){
                    st=mij+1;
                    rez=mij;
                }
                if(v[mij]==x){
                    rez=mij;
                    st=mij+1;
                }
                if(v[mij]>x){
                    dr=mij-1;
                }
            }
            if(rez==-2){
                fout<<"-1"<<endl;
            }
            else{
                fout<<rez+1<<endl;
            }
            }
        }
        if(c==2){
            st=0;
            dr=n;
            int rez=-2;
            if(v[n-1]==x){
                fout<<n;
            }
            else{
            while(st<=dr){
                int mij=st+((dr-st)/2);
                if(v[mij]<x){
                    st=mij+1;
                }
                if(v[mij]==x){
                    rez=mij;
                    dr=mij-1;
                }
                if(v[mij]>x){
                    dr=mij-1;
                    rez=mij;
                }
            }
            if(rez==-2){
                fout<<"-1"<<endl;
            }
            else{
                fout<<rez+1<<endl;
            }
            }
        }
    }
    return 0;
}