Advertisement
rudolf222222

dz

Sep 11th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. bool BinarySearch(const int* begin, const int* end, int target) {
  4.   int mid;
  5.   int begin_index;
  6.   int end_index;
  7.   int mid_index;
  8.   begin_index = 0;
  9.   end_index = end - begin;
  10.   while (end_index - begin_index > 1) {
  11.     mid = *(begin - 1 + (end_index + begin_index) / 2);
  12.     mid_index = (end_index + begin_index) / 2;
  13.     if (mid > target) {
  14.       end_index = mid_index;
  15.     } else if (mid < target) {
  16.       begin_index = mid_index;
  17.     } else if (mid == target) {
  18.       return true;
  19.     }
  20.   }
  21.   return (*(begin + begin_index - 1) == target ||
  22.           *(begin + end_index - 1) == target);
  23. }
  24.  
  25. int main() {
  26.   int arr_length;
  27.   std::cin >> arr_length;
  28.   int* arr = new int[arr_length];
  29.   int func_calls;
  30.   for (int i = 0; i < arr_length; i++) {
  31.     std::cin >> arr[i];
  32.   }
  33.   std::cin >> func_calls;
  34.   int begin;
  35.   int end;
  36.   int target;
  37.   for (int calls = 0; calls < func_calls; calls++) {
  38.     std::cin >> begin;
  39.     std::cin >> end;
  40.     std::cin >> target;
  41.     if (BinarySearch(&arr[begin], &arr[end], target)) {
  42.       std::cout << "YES\n";
  43.     } else {
  44.       std::cout << "NO\n";
  45.     }
  46.   }
  47.   delete[] arr;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement