Cod sursa(job #1210590)

Utilizator mariusn01Marius Nicoli mariusn01 Data 20 iulie 2014 15:50:23
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <vector>
#include <algorithm>

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

vector<int> v;
vector<int>::iterator it;

int n, i, x, m, t;

// lowerbound, prima mai mare sau egala
// upperbound, prima mai mare strict

int main() {
    fin>>n;
    for (i=1;i<=n;i++) {
        fin>>x;
        v.push_back(x);
    }

    fin>>m;
    for (i=1;i<=m;i++) {
        fin>>t>>x;
        if (t == 0) {

            // cea mai mare pozitie pe care se afla x
            it = upper_bound(v.begin(), v.end(), x);
            it --;
            if (*it == x)
                fout<<it-v.begin()+1<<"\n";
            else
                fout<<"-1\n";

        } else
            if (t == 1) {
            // cea mai mare pozitie pe care e un element <= x
                it = upper_bound(v.begin(), v.end(), x);
                it --;
                if (*it == x)
                    fout<<it-v.begin()+1<<"\n";
                else
                    fout<<"-1\n";

            }
            else {
                it = lower_bound(v.begin(), v.end(), x);
                if (*it == x)
                    fout<<it-v.begin()+1<<"\n";
                else
                    fout<<"-1\n";

            }
    }


    return 0;
}