Cod sursa(job #826389)

Utilizator BeilandArnoldArnold Beiland BeilandArnold Data 30 noiembrie 2012 17:34:18
Problema Cautare binara Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <vector>

inline long long int bs_lessoreq_max(long long int what, const std::vector<long long int> &where);
inline long long int bs_greateroreq_min(long long int what, const std::vector<long long int> &where);

int main(){
    std::ifstream fin("cautbin.in");
    std::ofstream fout("cautbin.out");
    long long int N;
    fin>>N;
    std::vector<long long int> sir(N);
    for(long long int i=0;i<N;++i) fin>>sir[i];
    fin>>N;
    for(long long int i=0;i<N;++i){
        char c;
        long long int x;
        fin>>c>>x;
        long long int temp;
        switch(c){
            case '0': temp=bs_lessoreq_max(x,sir);
                      if(sir[temp]==x) fout<<temp+1<<'\n'; else fout<<"-1\n";
                      break;
            case '1': fout<<bs_lessoreq_max(x,sir)+1<<'\n'; break;
            case '2': fout<<bs_greateroreq_min(x,sir)+1<<'\n';
        }
    }
}

inline long long int bs_lessoreq_max(long long int what, const std::vector<long long int> &where){
    long long int pos=0,step=1;
    for(;step<=where.size();step<<=1); step>>=1;
    for(;step;step>>=1)
        if(((pos|step)<where.size())&&where[pos|step]<=what) pos|=step;
    return pos;
}
inline long long int bs_greateroreq_min(long long int what, const std::vector<long long int> &where){
    long long int pos=where.size(),step=1;
    for(;step<=where.size();step<<=1); step>>=1;
    for(;step;step>>=1)
        if((pos&(~step))<where.size()&&where[pos&(~step)]>=what) pos&=(~step);
    return pos;
}