POJ 2823 单调队列入门题
2015-12-26 05:38
302 查看
【题目链接】
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=16694
【解题报告】
这题是可以用优先队列做的,这样会简单一些,不过考虑到是为了熟练的掌握斜率优化这一技巧,所以特意通过做这道题目来熟悉单调队列的基本用法。因为考虑到单调队列是从队尾插入,访问队首元素。所以使用了双端队列这一STL。虽然要比手写的模拟队列要麻烦一些(代码长了好多),不过思维上更加直观。
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=16694
【解题报告】
这题是可以用优先队列做的,这样会简单一些,不过考虑到是为了熟练的掌握斜率优化这一技巧,所以特意通过做这道题目来熟悉单调队列的基本用法。因为考虑到单调队列是从队尾插入,访问队首元素。所以使用了双端队列这一STL。虽然要比手写的模拟队列要麻烦一些(代码长了好多),不过思维上更加直观。
#include<iostream> #include<cstdio> #include<deque> #include<vector> using namespace std; struct node { int val,pos; }; int a[1000000+100]; int N,K; deque<node>q; void get_min() { q.clear(); for( int i=1; i<K; i++ ) { if( q.size() && i-q.front().pos>=K ) q.pop_front(); while( q.size() && q.back().val>=a[i] ) q.pop_back(); //删掉所有比他大的节点 node temp; temp.val=a[i]; temp.pos=i; q.push_back( temp ); } for( int i=K; i<=N; i++ ) { if( q.size() && i-q.front().pos>=K ) q.pop_front(); while( q.size() && q.back().val>=a[i] ) q.pop_back(); //删掉所有比他大的节点 node temp; temp.val=a[i]; temp.pos=i; q.push_back( temp ); printf( "%d ",q.front().val ); } puts(""); } void get_max() { q.clear(); for( int i=1; i<K; i++ ) { if( q.size() && i-q.front().pos>=K ) q.pop_front(); while( q.size() && q.back().val<=a[i] ) q.pop_back(); node temp; temp.val=a[i]; temp.pos=i; q.push_back( temp ); } for( int i=K; i<=N; i++ ) { if( q.size() && i-q.front().pos>=K ) q.pop_front(); while( q.size() && q.back().val<=a[i] ) q.pop_back(); node temp; temp.val=a[i]; temp.pos=i; q.push_back( temp ); printf( "%d ",q.front().val ); } puts(""); } int main() { while( ~scanf( "%d%d",&N,&K ) ) { for( int i=1; i<=N; i++ ) scanf( "%d",&a[i] ); get_min(); get_max(); } return 0; }
相关文章推荐
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1001
- POJ ACM 1002
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- POJ-2409-Let it Bead&&NYOJ-280-LK的项链
- POJ-1695-Magazine Delivery-dp
- POJ1523 SPF dfs
- POJ-1001 求高精度幂-大数乘法系列
- POJ-1003 Hangover
- POJ-1004 Financial Management
- 用单调栈解决最大连续矩形面积问题
- 2632 Crashing Robots的解决方法
- 1573 Robot Motion (简单题)
- POJ 1200 Crazy Search(简单哈希)
- 【高手回避】poj3268,一道很水的dijkstra算法题
- POJ 1088 滑雪
- poj2387 Til the Cows Come Home—Dijkstra模板