Advertisement
-nodo-

Divide et Impera!

Apr 6th, 2022 (edited)
1,482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <tuple>
  3.  
  4. using namespace std;
  5.  
  6. void input(int* arr, int n, bool rm) {
  7.     for (int i = 0; i < n; ++i) {
  8.         if (rm && i + 1 == n) {
  9.             arr[i] = arr[i - 1];
  10.             break;
  11.         }
  12.  
  13.         cout << "Podaj " << i + 1 << " liczbę: ";
  14.         cin >> arr[i];
  15.     }
  16. }
  17.  
  18. void out(int* arr, int n) {
  19.     cout << "[";
  20.     for (int i = 0; i < n - 1; ++i)
  21.         cout << arr[i] << ", ";
  22.    
  23.     cout << arr[n - 1] << "]" << endl;
  24. }
  25.  
  26. int ext(int* arr, int n, bool mini = true) {
  27.     int m = arr[0];
  28.     for (int i = 0; i < n; ++i) {
  29.         if (mini) {
  30.             if (arr[i] < m) m = arr[i];
  31.         } else {
  32.             if (arr[i] > m) m = arr[i];
  33.         }
  34.     }
  35.    
  36.     return m;
  37. }
  38.  
  39. tuple<int, int> conquer(int* arr, int n) {
  40.     int* low = new int[n / 2];
  41.     int* high = new int[n / 2];
  42.        
  43.     for (int i = 0; i < n / 2; i++) {
  44.         if (arr[i * 2] < arr[i * 2 + 1]) {
  45.             low[i] = arr[i * 2];
  46.             high[i] = arr[i * 2 + 1];
  47.         }
  48.        
  49.         else {
  50.             high[i] = arr[i * 2];
  51.             low[i] = arr[i * 2 + 1];
  52.         }
  53.     }
  54.    
  55.  
  56.     cout << "low: "; out(low, n / 2);
  57.     cout << "high: "; out(high, n /2);
  58.    
  59.     return { ext(low, n / 2),  ext(high, n / 2, false) };
  60.    
  61.     delete[] low;
  62.     delete[] high;
  63. }
  64.  
  65. int main() {
  66.     int n, min, max;
  67.     bool rm = false;
  68.  
  69.     cout << "Ile liczb: ";
  70.     cin >> n;
  71.  
  72.     if (n % 2 == 1) { n++; rm = true; }
  73.    
  74.     int *arr = new int[n];
  75.     input(arr, n, rm);
  76.  
  77.     tie(min, max) = conquer(arr, n);
  78.     cout << "min: " << min << endl << "max: " << max << endl << "rozpiętość: " << max - min << endl;
  79.    
  80.     delete[] arr;
  81.     return 0;
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement