POJ2823 Sliding Window (單調佇列的基本應用)

bigbigship發表於2014-12-16

題目連結:

http://poj.org/problem?id=2823


題意:

 給定一個長度為n的序列,求每個長度為k的區間的最大值與最小值


分析:

單調佇列的基本應用


程式碼如下:

<span style="font-size:14px;">#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;

const int maxn = 1000010;

int a[maxn];

int main()
{
    int n,k;
    while(~scanf("%d%d",&n,&k)){
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        deque<int > mmax;
        deque<int > mmin;
        for(int i=1;i<=n;i++){
            while(!mmin.empty()&&a[i]<a[mmin.back()]) mmin.pop_back();
            mmin.push_back(i);
            if(i>=k){
                while(!mmin.empty()&&mmin.front()<=i-k)
                    mmin.pop_front();
                if(i==n)
                    printf("%d\n",a[mmin.front()]);
                else
                    printf("%d ",a[mmin.front()]);
            }
        }
        for(int i=1;i<=n;i++){
            while(!mmax.empty()&&a[i]>a[mmax.back()]) mmax.pop_back();
            mmax.push_back(i);
            if(i>=k){
                while(!mmax.empty()&&mmax.front()<=i-k)
                    mmax.pop_front();
                if(i==n)
                    printf("%d\n",a[mmax.front()]);
                else
                    printf("%d ",a[mmax.front()]);
            }
        }
    }
    return 0;
}
</span>


相關文章