Cod sursa(job #1953074)

Utilizator kevtatarKevin Tatar kevtatar Data 4 aprilie 2017 17:09:05
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>

using namespace std;

int a[100],n;

ifstream f("cautbin.in");

struct raspuns{
    int val;
    int x;
};
raspuns r[10];

int valmax(int x){
    int lo = -1, hi = n, mid;
    while(hi-lo != 1){
        mid = (hi+lo)/2;
        if(a[mid] > x){
            hi = mid;
        }
        else{
            lo = mid;
        }
    }
    return lo;
}

int valmin(int x){
    int lo = -1, hi = n, mid;
    while(hi-lo != 1){
        mid = (hi+lo)/2;
        if(a[mid] >= x){
            hi = mid;
        }
        else{
            lo = mid;
        }
    }
    return hi;
}

int main()
{
    int nrr;

    f >> n;
    for(int i = 0; i < n; i++){
        f >> a[i];
    }
    f >> nrr;
    for(int i = 0; i < nrr; i++){
        f >> r[i].val >> r[i].x;
        switch(r[i].val){
            case 0: if(a[valmax(r[i].x)] != r[i].x){
                        cout << -1 << endl;
                    }
                    else cout << valmax(r[i].x)+1 << endl;
                    break;
            case 1: cout << valmax(r[i].x)+1 << endl; break;
            case 2: cout << valmin(r[i].x)+1 << endl; break;
        }
    }




    return 0;
}