Knobody

Untitled

Sep 4th, 2019
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <deque>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. // A Dequeue (Double ended queue) based method for printing maximum element of
  7. // all subarrays of size k
  8. void printKMax(int arr[], int n, int k)
  9. {
  10.     // Create a Double Ended Queue, Qi that will store indexes of array elements
  11.     // The queue will store indexes of useful elements in every window and it will
  12.     // maintain decreasing order of values from front to rear in Qi, i.e.,
  13.     // arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order
  14.     std::deque<int> Qi(k);
  15.  
  16.     /* Process first k (or first window) elements of array */
  17.     int i;
  18.     for (i = 0; i < k; ++i) {
  19.         // For every element, the previous smaller elements are useless so
  20.         // remove them from Qi
  21.         while ((!Qi.empty()) && arr[i] >= arr[Qi.back()])
  22.             Qi.pop_back(); // Remove from rear
  23.  
  24.         // Add new element at rear of queue
  25.         Qi.push_back(i);
  26.     }
  27.  
  28.     // Process rest of the elements, i.e., from arr[k] to arr[n-1]
  29.     for (; i < n; ++i) {
  30.         // The element at the front of the queue is the largest element of
  31.         // previous window, so print it
  32.         cout << arr[Qi.front()] << " ";
  33.  
  34.         // Remove the elements which are out of this window
  35.         while ((!Qi.empty()) && Qi.front() <= i - k)
  36.             Qi.pop_front(); // Remove from front of queue
  37.  
  38.         // Remove all elements smaller than the currently
  39.         // being added element (remove useless elements)
  40.         while ((!Qi.empty()) && arr[i] >= arr[Qi.back()])
  41.             Qi.pop_back();
  42.  
  43.         // Add current element at the rear of Qi
  44.         Qi.push_back(i);
  45.     }
  46.  
  47.     // Print the maximum element of last window
  48.     cout << arr[Qi.front()];
  49. }
  50.  
  51. // Driver program to test above functions
  52. int main()
  53. {
  54.     int arr[] = { 12, 1, 78, 90, 57, 89, 56 };
  55.     int n = sizeof(arr) / sizeof(arr[0]);
  56.     int k = 3;
  57.     printKMax(arr, n, k);
  58.     return 0;
  59. }
Add Comment
Please, Sign In to add comment