Queue-Monotonous Queue-Sliding Window

Total time limit: 12000ms

Memory limit: 65536kB

description

Given an array of length n (n<=10^6). There is a sliding window of size k that moves from the leftmost end to the rightmost end of the array. You can see the k numbers in the window. Each time the window slides to the right a number of distances.

Below is an example:

The array is [1 3 -1 -3 5 3 6 7], k = 3.

 

Window position Minimum Max
[1  3  -1] -3  5  3  6  7  -1 3
 1 [3  -1  -3] 5  3  6  7  -3 3
 1  3 [-1  -3  5] 3  6  7  -3 5
 1  3  -1 [-3  5  3] 6  7  -3 5
 1  3  -1  -3 [5  3  6] 7  3 6
 1  3  -1  -3  5 [3  6  7] 3 7



Your task is to get the maximum and minimum values ​​of the sliding window at each position.

 

enter

The input consists of two lines.
The first line includes n and k, which represent the length of the array and the size of the window, respectively.
The second line contains n numbers.

Output

The output includes two lines.
The first line contains the minimum value of each position the window moves from left to right.
The second line contains the maximum value of each position the window has moved from left to right.

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
#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
#include <deque>
using namespace std;

const int MAXN = 1e6;
int n, k;
int a[MAXN+5];

int main()
{
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; ++i)
        scanf("%d", &a[i]);

    /* min */
    deque<int> q;
    for (int i = 0; i < k-1; ++i) {
        while (!q.empty() && a[q.front()] > a[i])
            q.pop_front();
        q.push_front(i);
    }
    for (int i = k-1; i < n; ++i) {
        if (!q.empty() && i - q.back() >= k)
            q.pop_back();
        while (!q.empty() && a[q.front()] > a[i])
            q.pop_front();
        q.push_front(i);
        printf("%d ", a[q.back()]);
    }
    printf("\n");

    /* max */
    q.clear();
    for (int i = 0; i < k-1; ++i) {
        while (!q.empty() && a[q.front()] < a[i])
            q.pop_front();
        q.push_front(i);
    }    
    for (int i = k-1; i < n; ++i) {
        if (!q.empty() && i - q.back() >= k)
            q.pop_back();
        while (!q.empty() && a[q.front()] < a[i])
            q.pop_front();
        q.push_front(i);
        printf("%d ", a[q.back()]);
    }
    printf("\n");

    system("pause");
    return 0;
}

 【analysis】

Monotonous queue problem, very clever

You can look at this solution

Guess you like

Origin blog.csdn.net/w112348/article/details/108926409