POJ 2823 單調隊列入門題

【題目鏈接】
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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章