Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include <fstream>
  2.  
  3. using namespace std;
  4.  
  5. int binary_search (int* a, int l, int r, int k){
  6.     if (r >= l){
  7.         int idx = l + (r - l) / 2;
  8.         if (a[idx] == k){
  9.             return idx;
  10.         }
  11.         if (a[idx] > k) return binary_search(a, l, idx - 1, k);
  12.         return binary_search(a,idx+1,r, k);
  13.     }
  14.     return -1;
  15. }
  16.  
  17. int main() {
  18.     ifstream cin("binsearch.in");
  19.     ofstream cout("binsearch.out");
  20.     int n;
  21.     cin >> n;
  22.     int a[n];
  23.     for (int i = 0; i < n; i++) {
  24.         cin >> a[i];
  25.     }
  26.     int m;
  27.     cin >> m;
  28.     while(m != 0){
  29.         int x;
  30.         cin >> x;
  31.         int pos = binary_search(a,0,n-1,x);
  32.         int mn = pos, mx = pos;
  33.         if (pos == -1) cout << pos << " " << pos << endl;
  34.         else{
  35.             while (pos > 0){
  36.                 pos = binary_search(a,0,pos - 1,x);
  37.                 if (pos != -1) mn = pos;
  38.             }
  39.             pos = mx;
  40.             while (pos < n - 1 && pos > -1){
  41.                 pos = binary_search(a,pos + 1,n - 1,x);
  42.                 if (pos != -1) mx = pos;
  43.             }
  44.             cout << mn + 1 << " " << mx + 1 << endl;
  45.         }
  46.         m--;
  47.     }
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement