Advertisement
JosepRivaille

P84219: First occurrence

Mar 7th, 2016
714
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.65 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5.  
  6. int first_occurrence(double x, const vector<double>& v)
  7. {
  8.   int first = 0, last = v.size() - 1, it, mid;
  9.   int size = v.size();
  10.   while (size > 0) {
  11.     it = first;
  12.     mid = size/2;
  13.     it += mid;
  14.     if (v[it] < x) {
  15.       first = ++it;
  16.       size -= mid + 1;
  17.     }
  18.     else size = mid;
  19.   }
  20.   if (first < 0 || first >= v.size()) return -1;
  21.   if (v[first] != x) return -1;
  22.   return first;
  23. }
  24.  
  25.  
  26. int main()
  27. {
  28.   int n;
  29.   cin >> n;
  30.   vector<double> v(n);
  31.   for (int i = 0; i < n; ++i) cin >> v[i];
  32.   cin >> n;
  33.   cout << first_occurrence(n, v) << endl;
  34. }
  35.  
  36. //JosepRivaille
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement