码迷,mamicode.com
首页 > 编程语言 > 详细

滑动窗口(单调队列) C++版 Python版本

时间:2020-01-22 20:19:29      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:一个   algorithm   table   false   表数   span   版本   namespace   list   

AcWing 154 滑动窗口  https://www.acwing.com/problem/content/156/

 

给定一个大小为n106n≤106的数组。

有一个大小为k的滑动窗口,它从数组的最左边移动到最右边。

您只能在窗口中看到k个数字。

每次滑动窗口向右移动一个位置。

以下是一个例子:

该数组为[1 3 -1 -3 5 3 6 7],k为3。

窗口位置最小值最大值
[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

您的任务是确定滑动窗口位于每个位置时,窗口中的最大值和最小值。

输入格式

输入包含两行。

第一行包含两个整数n和k,分别代表数组长度和滑动窗口的长度。

第二行有n个整数,代表数组的具体数值。

同行数据之间用空格隔开。

输出格式

输出包含两个。

第一行输出,从左至右,每个位置滑动窗口中的最小值。

第二行输出,从左至右,每个位置滑动窗口中的最大值。

输入样例:

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

输出样例:

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




#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
const int N = 1e6+5;
int a[N], q[N]; //q这个队列一定要存下标

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n, k;
    cin >> n >> k;
    int L = 0, R = -1;
    for(int i = 0; i < n; ++ i)
    {
        cin >> a[i];

        while(L <= R && a[q[R]] >= a[i])   -- R;
        q[++R] = i;
         //判断队头是否出队
        if(L <= R && i - q[L] + 1 > k)
            ++ L;
        if(i + 1 >= k)
            cout << a[q[L]] << " ";
    }
    cout << endl;
    L = 0, R = -1;
    for(int i = 0; i < n; ++ i)
    {
        while(L <= R && a[q[R]] <= a[i])   -- R;
        q[++R] = i;
         //判断队头是否出队
        if(L <= R && i - q[L] + 1 > k)
            ++ L;
        if(i + 1 >= k)
            cout << a[q[L]] << " ";
    }
    return 0;
}

 

 

n, k = map(int, input().split())
a = list(map(int, input().split()))
q = [0 for i in range(n+5)]  # 注意队列存下表

L = 0
R = -1
for i in range(n):
    while L <= R and a[q[R]] >= a[i]:
        R -= 1
    R += 1
    q[R] = i
    if L <= R and i - q[L] + 1 > k:
        L += 1
    if i + 1 >= k:
        print(a[q[L]], end=" ")
print("")

L = 0
R = -1
for i in range(n):
    while L <= R and a[q[R]] <= a[i]:
        R -= 1
    R += 1
    q[R] = i
    if L <= R and i - q[L] + 1 > k:
        L += 1
    if i + 1 >= k:
        print(a[q[L]], end=" ")

滑动窗口(单调队列) C++版 Python版本

标签:一个   algorithm   table   false   表数   span   版本   namespace   list   

原文地址:https://www.cnblogs.com/Chaosliang/p/12229310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!