Cod sursa(job #2345687)

Utilizator Senth30Denis-Florin Cringanu Senth30 Data 16 februarie 2019 16:38:25
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>

using namespace std;
const int NMAX = 100005;

ifstream fin("cautbin.in");
ofstream fout("cautbin.out");

int N, M, cer, val;
int v[NMAX];

int read(){
    fin >> N;
    for(int i=0; i<N; i++)
        fin >> v[i];
}

int Search(int x, int y){
    if(v[x] == val) {
        return x;
    } else if(x + y == x) {
        return -1;
    } else {
        if(val>v[x])
            return Search(x + y, y/2);
        else if (val<v[x])
            return Search(x - y, y/2);
    }
}

int main(){

    read();
    fin >> M;
    for(int j=0; j<M; j++){
        fin >> cer >> val;
        int i = Search(N/2, N/2);
        if(cer == 0){
            if(i!=-1)
                while(v[i+1]==v[i])
                    i++;
        } else if(cer == 1){
            while(v[i+1]==v[i])
                i++;
        } else if(cer == 2){
            while(v[i-1]==v[i])
                i--;
        }
        fout << i+1 << endl;
    }

    return 0;
}