Cod sursa(job #642534)

Utilizator bmaticanBogdan-Alexandru Matican bmatican Data 1 decembrie 2011 16:43:25
Problema Cautare binara Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <complex>
#include <algorithm>

using namespace std;

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

int n;
vector<int> v(10, 0);

pair<int, bool> binsearch(int val, int l, int r) {
  int m = l + (r - l) / 2;
  if (v[m] == val) {
    return make_pair(m, true);
  }

  if (m == l) {
    return make_pair(m, false);
  }

  if (v[m] < val) {
    return binsearch(val, m + 1, r);
  } else {
    return binsearch(val, l, m - 1);
  }
}

void solve() {
  in >> n;
  v.resize(n, 0);
  v[0] = -1;
  int temp;

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

  sort(v.begin(), v.end());

  int m;
  in >> m;
  int x, y;
  while (m--) {
    in >> x >> y;
    pair<int, bool> res = binsearch(y, 0, n - 1);
    int pos = res.first;
    int i = pos;
    switch (x) {
    case 0:
      if (false == res.second) {
        out << -1 << endl;
      } else {
        while (i <= n && y == v[i]) ++i;
        out << i - 1 << endl;
      }
      break;
    case 1:
      if (true == res.second) {
        while (i <= n && y == v[i]) ++i;
        out << i - 1 << endl;
      } else {
        if (v[pos] > y) {
          while (y < v[i]) --i;
          out << i << endl;
        } else {
          while (i <= n && y > v[i]) ++i;
          out << i - 1 << endl;
        }
      }
      break;
    case 2:
      if (true == res.second) {
        while (i > 0 && y == v[i]) --i;
        out << i + 1 << endl;
      } else {
        if (v[pos] > y) {
          while (i > 0 && y < v[i]) --i;
          out << i + 1 << endl;
        } else {
          while (y > v[i]) ++i;
          out << i << endl;
        }
      }
      break;
    default:
      cerr << "problem\n";
      break;
    }
  }
}

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