Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define fast ios_base::sync_with_stdio(false);cin.tie(NULL)
- #define read freopen("input.txt","r",stdin)
- #define write freopen("output.txt","w",stdout)
- int binary_search(int *arr, int low, int high, int target)
- {
- while(low <= high)
- {
- int mid = low + (high - low) / 2;
- if(arr[mid] == target)
- return mid;
- else if(arr[mid] < target)
- low = mid + 1;
- else
- high = mid - 1;
- }
- return -1;
- }
- int lower_bound(int *arr, int low, int high, int target)
- {
- while(low <= high)
- {
- int mid = low + (high - low) / 2;
- if(arr[mid] < target)
- low = mid + 1;
- else
- high = mid - 1;
- }
- return low;
- }
- int upper_bound(int *arr, int low, int high, int target)
- {
- while(low <= high)
- {
- int mid = low + (high - low) / 2;
- if(arr[mid] <= target)
- low = mid + 1;
- else
- high = mid - 1;
- }
- return low;
- }
- int first_occurence(int *arr, int low, int high, int target)
- {
- while(low <= high)
- {
- int mid = low + (high - low) / 2;
- if(arr[mid] < target)
- low = mid + 1;
- else
- high = mid - 1;
- }
- if(arr[low] == target)
- return low;
- else
- return -1;
- }
- int last_occurence(int *arr, int low, int high, int target)
- {
- while(low <= high)
- {
- int mid = low + (high - low) / 2;
- if(arr[mid] <= target)
- low = mid + 1;
- else
- high = mid - 1;
- }
- if(arr[high] == target)
- return high;
- else
- return -1;
- }
- int main()
- {
- #ifndef ONLINE_JUDGE
- read;
- write;
- #endif
- fast;
- int arr[] = {6, 6, 7, 9, 9, 9, 9, 10, 15, 17, 22};
- int n = sizeof(arr) / sizeof(arr[0]);
- int x = binary_search(arr, 0, n - 1, 9);
- int lb = lower_bound(arr, 0, n - 1, 9);
- int ub = upper_bound(arr, 0, n - 1, 9);
- int fo = first_occurence(arr, 0, n - 1, 9);
- int lo = last_occurence(arr, 0, n - 1, 9);
- cout << x << ' ' << lb << ' ' << ub << ' ' << fo << ' ' << lo << endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment