POJ 2823 Sliding Window(优先队列)
2016-01-02 16:23
295 查看
Description
给定一个大小已知的数组以及一个大小已知的滑动窗口,窗口每个时刻向后移动一位,求出每个时刻窗口中数字的最大值和最小值
Input
第一行为两个整数n和k分别表示数组长度和窗口长度,第二行为n个整数表示数组
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
Solution
使用STL中的优先队列priority_queue进行求解。开两个优先队列,优先队列中插入的是元素的下标,队列中按元素值的从大到小和从小到大优先放在上面。每插入一个元素后,将队列中已经跑出窗口外的元素删除,队列的top元素所指的元素就是该窗口内的最大或最小值
Code
给定一个大小已知的数组以及一个大小已知的滑动窗口,窗口每个时刻向后移动一位,求出每个时刻窗口中数字的最大值和最小值
Input
第一行为两个整数n和k分别表示数组长度和窗口长度,第二行为n个整数表示数组
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
Solution
使用STL中的优先队列priority_queue进行求解。开两个优先队列,优先队列中插入的是元素的下标,队列中按元素值的从大到小和从小到大优先放在上面。每插入一个元素后,将队列中已经跑出窗口外的元素删除,队列的top元素所指的元素就是该窗口内的最大或最小值
Code
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<queue> #include<vector> using namespace std; #define maxn 1000010 int a[maxn],mmax[maxn],mmin[maxn]; struct cmp1 { bool operator()(const int x,const int y) { return a[x]<a[y]; } }; struct cmp2 { bool operator()(const int x,const int y) { return a[x]>a[y]; } }; priority_queue<int,vector<int>,cmp1>Q1;//元素从小到大排 priority_queue<int,vector<int>,cmp2>Q2;//元素从大到小排 int main() { int n,k; scanf("%d%d",&n,&k); if(k>n) k=n; int s1=0,s2=0; for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=1;i<=k;i++)//先让前k个元素入队 Q1.push(i),Q2.push(i); mmax[s1++]=a[Q1.top()];//从队列首取出最大值 mmin[s2++]=a[Q2.top()];//从队列首取出最小值 for(int i=k+1;i<=n;i++) { Q1.push(i);//入队 Q2.push(i);//入队 while(i-Q1.top()>=k)//让跑出窗口外的元素出队 Q1.pop(); mmax[s1++]=a[Q1.top()];//从队列首取出最大值 while(i-Q2.top()>=k)//让跑出窗口外的元素出队 Q2.pop(); mmin[s2++]=a[Q2.top()];//从队列首取出最小值 } for(int i=0;i<=n-k;i++)//输出最小值 printf("%d%c",mmin[i],i<n-k?' ':'\n'); for(int i=0;i<=n-k;i++)//输出最大值 printf("%d%c",mmax[i],i<n-k?' ':'\n'); return 0; }
相关文章推荐
- iOS渐隐渐现效果跳转
- 图形学中的Hermite曲线
- CodeForces 379A Valera and Plates
- 细说grep命令
- jquery实现简单的全选和反选功能
- 记录点滴,留给记忆
- java登陆注册界面参考的资料和代码
- HMM 传统后向算法
- FPGA笔记 Altera Cyclone系列FPGA资源介绍
- grep、egrep
- 【设计模式】代理模式
- 多文件夹下编写Makefile详解
- C#之方法与函数
- Proximal Gradient Method近端梯度算法
- jquery中focus()函数实现当对象获得焦点后自动把光标移到内容最后
- NSTimer的使用以及NSTimer暂停和继续
- 【VBA研究】查找目录以下全部文件的名称
- 蓝桥杯 算法训练 未名湖边的烦恼
- 【ZYNQ-7000开发之八】OLED的驱动
- Java 图片提取RGB数组 RGBOfCharMaps (整理)