Advertisement
Evirir

Untitled

Dec 23rd, 2018
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6.     ios_base::sync_with_stdio(0); cin.tie(0);
  7.    
  8.     int n=4;
  9.     int arr[] = {0,0,1,2,3,3,4,4,9};
  10.     int arrsize = sizeof(arr)/sizeof(arr[0]);
  11.    
  12.     //binary search the leftmost position that contains n
  13.     //L = minimum, R = maximum, ans = to store ans once it's found, then continue searching for left-er answers
  14.     int L=0,R=arrsize,m,ans;
  15.    
  16.     while(L<=R){
  17.         m=(L+R)/2;
  18.        
  19.         //if m is answer or larger: search leftside
  20.         if(arr[m]>=n){
  21.             ans=m;
  22.             R=m-1;
  23.         }
  24.        
  25.         //if m is smaller: search rightside
  26.         else L=m+1;
  27.     }
  28.    
  29.     cout<<"The leftmost position that contains " << n << ": " << ans+1 << '\n';
  30.    
  31.     return 0;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement