POJ2823

来源:互联网 发布:地理专业知乎 编辑:程序博客网 时间:2024/06/05 07:48
Sliding Window
Time Limit: 12000MSMemory Limit: 65536KTotal Submissions: 54605Accepted: 15693Case Time Limit: 5000MS

Description

An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example: 
The array is [1 3 -1 -3 5 3 6 7], and k is 3.Window positionMinimum valueMaximum value[1  3  -1] -3  5  3  6  7 -13 1 [3  -1  -3] 5  3  6  7 -33 1  3 [-1  -3  5] 3  6  7 -35 1  3  -1 [-3  5  3] 6  7 -35 1  3  -1  -3 [5  3  6] 7 36 1  3  -1  -3  5 [3  6  7]37

Your task is to determine the maximum and minimum values in the sliding window at each position. 

Input

The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line. 

Output

There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values. 

Sample Input

8 31 3 -1 -3 5 3 6 7

Sample Output

-1 -3 -3 -3 3 33 3 5 5 6 7
今天做校队选拔赛时遇到了一道用单调队列的题,于是找了这道题来学习一下单调队列的用法~
紫书P241页也有相关的用法。
#include <iostream>#include <cstdio>#include <queue>#include <deque>using namespace std;typedef pair<int,int> Pii;const int maxn=1000005;deque<Pii> q1;deque<Pii> q2;int n,k;int mi[maxn],ma[maxn];int main(){    while(scanf("%d%d",&n,&k)!=EOF)    {        q1.clear();        q2.clear();        int x;        for(int i=1;i<=n;i++)        {            scanf("%d",&x);            while(!q1.empty()&&q1.back().first>=x)                q1.pop_back();            q1.push_back(Pii(x,i));            if(i>=k)            {                while(!q1.empty()&&q1.front().second<=i-k)                    q1.pop_front();                mi[i]=q1.front().first;            }            while(!q2.empty()&&q2.back().first<=x)                q2.pop_back();            q2.push_back(Pii(x,i));            if(i>=k)            {                while(!q2.empty()&&q2.front().second<=i-k)                    q2.pop_front();                ma[i]=q2.front().first;            }        }        for(int i=k;i<n;i++)            printf("%d ",mi[i]);        printf("%d\n",mi[n]);        for(int i=k;i<n;i++)            printf("%d ",ma[i]);        printf("%d\n",ma[n]);    }    return 0;}

0 0
原创粉丝点击