Cod sursa(job #2284865)

Utilizator Dusceac_Bogdan24Dusceac Bogdan Dusceac_Bogdan24 Data 17 noiembrie 2018 18:20:00
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");
int main()
{
    int N,M,mid,st,dr,i,x,intr,pozx,j,r;
    fin>>N;
    int v[N+3];
    st=1;
    dr=N;
    for(i=1;i<=N;i++){
        fin>>v[i];
    }
    fin>>M;
    for(i=1;i<=M;i++){
        fin>>intr>>x;
        st=1;
        dr=N;
        while(st<dr){
            mid=st+(dr-st+1)/2;
            if(v[mid]>x)
                dr=mid-1;
            else
                st=mid;
        }
        pozx=dr;
        if(intr!=2){
            if(v[pozx]==x){
                fout<<pozx<<endl;
            }
            else{
                if(intr==0){
                    fout<<-1<<endl;
                }
                if(intr==1){
                    j=1;
                    while(x>v[j]){
                        r=j;
                        j++;
                    }
                    fout<<r<<endl;
                }
            }
        }
        if(intr==2){
            if(v[pozx]==x){
                j=0;
                while(x==v[pozx-j]){
                    r=pozx-j;
                        j++;
                    }
                    fout<<r<<endl;
            }
            else{
                j=N;
                while(x<v[j]){
                    r=v[j];
                    j--;
                }
                fout<<r<<endl;
            }

        }
    }

    return 0;
}