您的位置:首页 > 其它

POJ 2823 单调队列入门题

2015-12-26 05:38 302 查看
【题目链接】

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj