Cod sursa(job #2252159)

Utilizator AlexandruGabrielAliciuc Alexandru AlexandruGabriel Data 2 octombrie 2018 13:39:51
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

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

int main()
{
    vector <long long> v;
    int n, m, op;
    long long x;
    fin >> n;
    for (int i = 0; i < n; i++)
    {
        fin >> x;
        v.push_back(x);
    }
    fin >> m;
    for (int i = 1; i <= m; i++)
    {
        fin >> op >> x;
        if (op == 0)
        {
            int ind  = upper_bound(v.begin(), v.end(), x) - v.begin() - 1;
            if (v[ind] != x)
            {
                fout << -1 << "\n";
            }
            else fout << ind + 1 << "\n";
        }
        else if (op == 1)
        {
            if (binary_search(v.begin(), v.end(), x))
                fout << upper_bound(v.begin(), v.end(), x) - v.begin() << "\n";
            else fout << lower_bound(v.begin(), v.end(), x) - v.begin() << "\n";
        }
        else if (op == 2)
        {
            if (binary_search(v.begin(), v.end(), x))
            {
                fout << lower_bound(v.begin(), v.end(), x) - v.begin() + 1 << "\n";
            }
            else fout << upper_bound(v.begin(), v.end(), x) - v.begin() + 1 << "\n";
        }
    }
    return 0;
}