POJ - 2823 Sliding Window (滑动窗口入门)
Posted lis-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ - 2823 Sliding Window (滑动窗口入门)相关的知识,希望对你有一定的参考价值。
An array of size n ≤ 10 6 is given to you. There is a sliding window of size kwhich 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.
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
题意:给出n个数和区间长度m,然后求每个长度为m的区间的最大值和最小值
思路:因为题目所给的范围比较大,nlogn算法其实也可以,因为只有一组数据,但是我们把他作为滑动窗口的入门题来进行解析,滑动窗口是一个求一个区间的的值,区间长度固定的一个o(n)算法
下面首先我们熟悉下双端队列
头文件 #include<deque>
定义 deque<int> q;
头部插入 q.push_front()
头部删除 q.pop_front()
尾部插入 q.push_back()
尾部删除 q.pop_back()
取头值 q.front()
取尾值 q.back()
滑动窗口是一个维护一个队列,里面存的是最大值下表
最前的那个是当前区间最大值
给出一个例子
5 6 4 9 1
我们区间长度为2
开始5进入队列,然后因为6比5大,5就被踢出队列,6进来,因为队列最前面的就是区间里的最大值
然后4也到6得后面,因为如果6出去了,4就是当前得最大值了
后面9比4和6都大,就可以替换掉前面得数
主要思想:按顺序保存一个单调递减得序列,比他大得直接更新,小的后面区间用的到得一种思想,然后判断下标是否出区间就可以,每个数都最多进队列一次,出队列一次
然后这个提我们用两个双端队列 一个维护最大值,一个最小值即可
#include<cstdio> #include<cstring> #include<cmath> #include<iostream> #include<deque> #include<vector> #include<algorithm> using namespace std; int n,m; int a[1000001]; int b[1000001]; int c[1000001]; deque<int> qx,qn; int cnt; int main() { while(scanf("%d%d",&n,&m)!=EOF) { while(!qx.empty()) qx.pop_front(); while(!qn.empty()) qn.pop_front(); for(int i=0;i<n;i++) scanf("%d",&a[i]); for(int i=0;i<n;i++) { while(!qx.empty()&&a[i]>=a[qx.back()])//判断是否新加得数比前面得大,大的话我们就要把最大值放最前, qx.pop_back(); qx.push_back(i); while(!qn.empty()&&a[i]<=a[qn.back()]) qn.pop_back(); qn.push_back(i); if(i>=m-1) { while(!qx.empty()&&qx.front()<=i-m) qx.pop_front();//我们把出了区间的数踢出队列 b[cnt]=a[qx.front()]; while(!qn.empty()&&qn.front()<=i-m) qn.pop_front(); c[cnt++]=a[qn.front()]; } } for(int i=0;i<cnt;i++) { if(i==0) printf("%d",c[i]); else printf(" %d",c[i]); } printf(" "); for(int i=0;i<cnt;i++) { if(i==0) printf("%d",b[i]); else printf(" %d",b[i]); } printf(" "); } }
以上是关于POJ - 2823 Sliding Window (滑动窗口入门)的主要内容,如果未能解决你的问题,请参考以下文章