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长度大小的窗口,窗口按照从左到右的顺序移动,每一栋一次,求出窗口这个数列里面的最大值和最小值,然后将他们分别输出

思路:怎么说呢,一个板子题,你如果知道这种算法,你应该就会写,不知道,也就很难写出来,看了一下午的视频,也没太理解其意思,不过这种板子题打多了也就理解了

AC代码:

#include
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(;ia[i])//对首id<=队尾id,并且入队元素比队尾元素大,删掉
            r--;
        q[++r]=i;
    }
    for(;ia[i])
            r--;
        q[++r]=i;
        printf("%d ",a[q[l]]);
    }
    puts("");
    return ;
}
void slove_max()
{
    int l=1,r=0,i=0;//左为队首,右为队尾
    for(;i

你可能感兴趣的:(G - Sliding Window 滑动窗口)