POJ 2823.Sliding Window

版权声明:本文为博主原创文章,记录蒟蒻的成长之路,欢迎吐槽~ https://blog.csdn.net/PegasiTIO/article/details/89415497

Description

An array of size

n ≤ 10^6

is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example:

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

Window position Minimum value Maximum value
[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 determine the maximum and minimum values in the sliding window at each position.

Input

The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line.

Output

There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values.

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

单调队列

LeetCode 239.滑动窗口最大值多输出一个最小值,别的完全一样

PS:cin,cout超时

#include <vector>
#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 1000005;
int minq[maxn], maxq[maxn], nums[maxn];
vector<int> ans1, ans2;

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

    int l1 = 1, r1 = 1, l2 = 1, r2 = 1;
    for (int i = 1; i <= n; ++i)
    {
        //弹出超界元素
        while (l1 <= r1 && minq[l1] <= i - k)
            ++l1;
        while (l2 <= r2 && maxq[l2] <= i - k)
            ++l2;

        //弹出大的元素
        while (l1 <= r1 && nums[i] < nums[minq[r1]])
            --r1;
        minq[++r1] = i;
        
        //弹出小的元素
        while (l2 <= r2 && nums[i] > nums[maxq[r2]])
            --r2;
        maxq[++r2] = i;

        if (i >= k)
        {
            ans1.push_back(nums[minq[l1]]);
            ans2.push_back(nums[maxq[l2]]);
        }
    }

    for (int i = 0; i < ans1.size(); ++i)
        printf("%d ", ans1[i]);
    printf("\n");
    for (int i = 0; i < ans2.size(); ++i)
        printf("%d ", ans2[i]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PegasiTIO/article/details/89415497