天天看點

G - Sliding Window 滑動視窗

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

Window position Maximum value
[1 3 -1] -3 5 3 6 7 -1
1 [3 -1 -3] 5 3 6 7 -3
1 3 [-1 -3 5] 3 6 7 -3
1 3 -1 [-3 5 3] 6 7 -3
1 3 -1 -3 [5 3 6] 7 3
1 3 -1 -3 5 [3 6 7 3
Maximum value
3
3
5
5
6
7

Your task is to determine the maximum and minimum values in the sliding window at each position.

輸入:

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.

輸出:

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.

樣例:

輸入:

8 3

1 3 -1 -3 5 3 6 7

輸出:

-1 -3 -3 -3 3 3

3 3 5 5 6 7

題意:給n個數,然後給一個k長度大小的視窗,視窗按照從左到右的順序移動,每一棟一次,求出視窗這個數列裡面的最大值和最小值,然後将他們分别輸出

#include<cstdio>
using namespace std;
//單調隊列
const int maxn=1e6+10;
int n,k,q[maxn],a[maxn];
void slove_min()
{
    int l=1,r=0,i=0;//左為隊首,右為隊尾
    for(;i<k-1;i++)
    {
        while(l<=r&&a[q[r]]>a[i])//對首id<=隊尾id,并且入隊元素比隊尾元素大,删掉
            r--;
        q[++r]=i;
    }
    for(;i<n;i++)
    {
        if(q[l]<=i-k)
            l++;
        while(l<=r&&a[q[r]]>a[i])
            r--;
        q[++r]=i;
        printf("%d ",a[q[l]]);
    }
    puts("");
    return ;
}
void slove_max()
{
    int l=1,r=0,i=0;//左為隊首,右為隊尾
    for(;i<k-1;i++)
    {
        while(l<=r&&a[q[r]]<a[i])//對首id<=隊尾id,并且入隊元素比隊尾元素小,删掉
            r--;
        q[++r]=i;
    }
    for(;i<n;i++)
    {
        if(q[l]<=i-k)
            l++;
        while(l<=r&&a[q[r]]<a[i])
            r--;
        q[++r]=i;
        printf("%d ",a[q[l]]);
    }
    puts("");
    return ;
}
int main()
{
    while(~scanf("%d %d",&n,&k))
    {
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        slove_min();
        slove_max();
    }

}