滑动窗口(单调队列)

问题描述

ZJM 有一个长度为 n 的数列和一个大小为 k 的窗口, 窗口可以在数列上来回移动. 现在 ZJM 想知道在窗口从左往右滑的时候,每次窗口内数的最大值和最小值分别是多少. 例如:
数列是 [1 3 -1 -3 5 3 6 7], 其中 k 等于 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

Input

输入有两行。第一行两个整数n和k分别表示数列的长度和滑动窗口的大小,1<=k<=n<=1000000。第二行有n个整数表示ZJM的数列。

Output

输出有两行。第一行输出滑动窗口在从左到右的每个位置时,滑动窗口中的最小值。第二行是最大值。

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

解题思路

这道题要查找一个窗口的最大值和最小值,这是一种局部的概念,恰好单调队列可以维护局部的单调性,因此这类题均可以使用单调队列来求解。单调队列原理及其简单,看下面伪代码即可理解。

单调队列伪代码:

INITIALIZE queue
FOR each element u DO
	WHILE queue.size() > 0 AND queue.front() does not belong to the interval DO
		queue.pop_front()//当超出窗口限制时弹出队首
	END
	WHILE queue.size() > 0 AND queue.back() > u DO
		queue.pop_back()//当不满足单调性时弹出队尾
	END
	queue.push(u)
END		

由于单调队列时从队尾进,不符合要求的也从队尾出,只有超出区间限制的才从队首出,所以这道题不能只用一次单调队列了,我们只能先用一个单调递增队列来求出窗口的最小值,再用一个单调递减队列来求出窗口的最大值。两个值都处于单调队列的队首。

PS:函数过多别忘了加inline,否则直接超时。不用函数直接全写到main中中也可以。

完整代码

//#pragma GCC optimize(2)//比赛禁止使用!
//#pragma G++ optimize(2)
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;

const int maxn=1000000+10;
int n,k,a[maxn],q[maxn],Max[maxn],Min[maxn];

inline int getint()
{
    int x=0,s=1;
    char ch=' ';
    while(ch<'0' || ch>'9')
    {
        ch=getchar();
        if(ch=='-') s=-1;
    }
    while(ch>='0' && ch<='9')
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x*s;
}
inline void incqueue()
{
    int l=1,r=0;
    for (int i=1; i<=n; i++)
    {
        while(r >= l && a[q[r]] >= a[i])//维护单调递增队列
            r--;//弹出队尾

        q[++r]=i;//存储下标

        if(q[r]-q[l]+1 > k)//维护队列长度,防止超过k
            l++;

        Min[i]=a[q[l]];
    }
}
inline void decqueue()
{
    int l=1,r=0;
    for (int i=1; i<=n; i++)
    {
        while(r >= l && a[q[r]] <= a[i])//维护单调递减队列
            r--;//弹出队尾

        q[++r]=i;//存储下标

        if(q[r]-q[l]+1 > k)//维护队列长度,防止超过k
            l++;

        Max[i]=a[q[l]];
    }
}
inline void output()
{
    for (int i=k; i<=n; i++)
    {
        printf("%d ",Min[i]);
    }
    putchar('\n');
    for (int i=k; i<=n; i++)
    {
        printf("%d ",Max[i]);
    }
    putchar('\n');
}
int main()
{
    n=getint(); k=getint();
    for (int i=1; i<=n; i++)
        a[i]=getint();

    incqueue();
    decqueue();

    output();

    return 0;
}
发布了32 篇原创文章 · 获赞 24 · 访问量 2227

猜你喜欢

转载自blog.csdn.net/weixin_43347376/article/details/105058295
今日推荐