POJ2823
来源:互联网 发布:地理专业知乎 编辑:程序博客网 时间:2024/06/05 07:48
Sliding Window
Time Limit: 12000MSMemory Limit: 65536KTotal Submissions: 54605Accepted: 15693Case Time Limit: 5000MS
Description
An array of size n ≤ 106 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 [1 3 -1] -3 5 3 6 7 -13 1 [3 -1 -3] 5 3 6 7 -33 1 3 [-1 -3 5] 3 6 7 -35 1 3 -1 [-3 5 3] 6 7 -35 1 3 -1 -3 [5 3 6] 7 36 1 3 -1 -3 5 [3 6 7]37
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
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 31 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 33 3 5 5 6 7
今天做校队选拔赛时遇到了一道用单调队列的题,于是找了这道题来学习一下单调队列的用法~
紫书P241页也有相关的用法。
#include <iostream>#include <cstdio>#include <queue>#include <deque>using namespace std;typedef pair<int,int> Pii;const int maxn=1000005;deque<Pii> q1;deque<Pii> q2;int n,k;int mi[maxn],ma[maxn];int main(){ while(scanf("%d%d",&n,&k)!=EOF) { q1.clear(); q2.clear(); int x; for(int i=1;i<=n;i++) { scanf("%d",&x); while(!q1.empty()&&q1.back().first>=x) q1.pop_back(); q1.push_back(Pii(x,i)); if(i>=k) { while(!q1.empty()&&q1.front().second<=i-k) q1.pop_front(); mi[i]=q1.front().first; } while(!q2.empty()&&q2.back().first<=x) q2.pop_back(); q2.push_back(Pii(x,i)); if(i>=k) { while(!q2.empty()&&q2.front().second<=i-k) q2.pop_front(); ma[i]=q2.front().first; } } for(int i=k;i<n;i++) printf("%d ",mi[i]); printf("%d\n",mi[n]); for(int i=k;i<n;i++) printf("%d ",ma[i]); printf("%d\n",ma[n]); } return 0;}
0 0
- poj2823
- POJ2823
- poj2823
- poj2823
- POJ2823
- poj2823
- poj2823
- POJ2823
- poj2823
- POJ2823
- POJ2823
- poj2823(ST)
- poj2823(堆)
- poj2823 单调队列
- 单调队列 POJ2823
- 單調隊列::poj2823 Sliding Window
- poj2823 Sliding Window
- 单调队列 (POJ2823)
- 比赛心得
- BAPC2014 K题 Key to Knowledge(中途相遇法,hash,状态压缩)
- hibernate映射的数据类型
- c++构造函数,拷贝构造函数,赋值构造函数
- Session的原理
- POJ2823
- PHP编程效率的50个要点
- Android 一种遍历ViewGroup的方法
- 子类向上抛异常问题
- 圆角绘制引发的离屏渲染
- Light oj 1045 (求某个数的阶乘在x进制下的位数)
- JS Object.keys()
- Linux系统下的3个文件时间
- Java基础类型与其二进制表示