Programming thinking week5 homework D-sliding window

topic

ZJM has a sequence of length n and a window of size k. The window can move back and forth on the sequence. Now ZJM wants to know when the window slides from left to right, the maximum and minimum values ​​of the number in the window each time how many.
Insert picture description here

Input

There are two lines of input. The two integers n and k in the first row represent the length of the sequence and the size of the sliding window, 1 <= k <= n <= 1000000. In the second row, there are n integers representing the sequence of ZJM.

Output

The output has two lines. The first line outputs the minimum value of the sliding window at each position from left to right. The second line is the maximum value.

Sample Input

8 3
1 3 -1 -3 5 3 6 7

Sample Output

1 -3 -3 -3 3 3
3 3 5 5 6 7

Ideas

Use monotonous queues.
The maintenance process of a monotonic queue is similar to the monotonic stack, except that:

  • The monotonic stack maintains only one end (top of the stack), while the monotonous queue can maintain both ends (first and last)
  • Monotonic stacks generally maintain global monotonicity, while monotonic queues generally maintain local monotonicity. Monotonic stack size has no upper limit, while monotonic queues usually have size limits

Use the monotonically decreasing queue to find the maximum value in the window, and use the monotonically increasing queue to find the minimum value in the window.
When looping to the i-th time, the head of the team is the processing result of the first k elements, that is, the smallest / largest of the first k elements.

Code

#include <cstdio>
#include <queue>
using namespace std;
int a[1000005];
deque<int> q;

int main() {
    int n,k;
    scanf("%d%d",&n,&k);
    for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
    for(int i=0;i<n;i++){
        while (q.size()>0&&q.front()<i-k+1)
            q.pop_front();
        while (q.size()>0&&a[q.back()]>a[i])
            q.pop_back();
        q.push_back(i);
        if(i>=k-1)
            printf("%d ",a[q.front()]);
    }
    q.clear();
    printf("\n");
    for(int i=0;i<n;i++){
        while(q.size()>0&&q.front()<i-k+1)
            q.pop_front();
        while(q.size()>0&&a[q.back()]<a[i])
            q.pop_back();
        q.push_back(i);
        if(i>=k-1)
            printf("%d ",a[q.front()]);
    }
    return 0;
}

Title link

Published 24 original articles · praised 2 · visits 435

Guess you like

Origin blog.csdn.net/weixin_43805228/article/details/105174886