Cod sursa(job #642554)

Utilizator bmaticanBogdan-Alexandru Matican bmatican Data 1 decembrie 2011 17:19:10
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <complex>
#include <algorithm>

using namespace std;

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

void solve() {
  int n;
  in >> n;
  int v[n + 1];
  v[0] = -1;

  int temp;
  for (int i = 1; i <= n; ++i) {
    in >> temp;
    v[i] = temp;
  }

  sort(v + 1, v + n + 1);

  int m;
  in >> m;

  int x, y;
  while (m--) {
    in >> x >> y;
    int it;
    switch(x) {
      case 0:
        it = upper_bound(v + 1, v + n + 1, y) - v - 1;
        if (it >= 1 && it <= n && v[it] == y) {
          out << it << endl;
        } else {
          out << -1 << endl;
        }
        break;
      case 1:
        it = lower_bound(v + 1, v + n + 1, y + 1) - v - 1;
        out << it << endl;
        break;
      case 2:
        it = upper_bound(v + 1, v + n + 1, y - 1) - v;
        out << it << endl;
        break;
    }
  }
}

int main() {
  solve();
  return 0;
}