Cod sursa(job #2345725)

Utilizator Senth30Denis-Florin Cringanu Senth30 Data 16 februarie 2019 17:17:07
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 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, Z;
unsigned int v[NMAX];

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

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

int Search_2(int x, int y){
    if(v[x] <= val) {
        Z = x;
        if(x + y != x)
            return Search_1(x + y, y/2);
    } else {
        if(val>v[x])
            return Search_1(x + y, y/2);
        else if (val<v[x])
            return Search_1(x - y, y/2);
    }
}

int Search_3(int x, int y){
    if(v[x] >= val) {
        Z = x;
        if(x + y != x)
            return Search_1(x - y, y/2);
    } else {
        if(val>v[x])
            return Search_1(x + y, y/2);
        else if (val<v[x])
            return Search_1(x - y, y/2);
    }
}

int main(){

    read();
    fin >> M;
    for(int j=0; j<M; j++){
        fin >> cer >> val;
        Z=-2;
        if(cer == 0){
            Search_1(N/2, N/2);
        } else if(cer == 1){
            Search_2(N/2, N/2);
        } else if(cer == 2){
            Search_3(N/2, N/2);
        }
        fout << Z+1 << endl;
    }

    return 0;
}