poj 2823 Sliding Window 题解

来源:互联网 发布:手机微信java通用版 编辑:程序博客网 时间:2024/06/01 17:46
Sliding Window
Time Limit: 12000MS Memory Limit: 65536KTotal Submissions: 53037 Accepted: 15207Case 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

Source

POJ Monthly--2006.04.28, Ikki

[Submit]   [Go Back]   [Status]   [Discuss]

Home Page   Go Back  To top

————————————————————————我是分割线————————————————————————————————

单调队列模板题。

维护两个单调队列,一个单调增,一个单调减。

 1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 #include<queue> 7 #include<cstdlib> 8 #include<iomanip> 9 #include<cassert>10 #include<climits>11 #define maxn 100000112 #define F(i,j,k) for(int i=j;i<=k;i++)13 #define M(a,b) memset(a,b,sizeof(a))14 #define FF(i,j,k) for(int i=j;i>=k;i--)15 #define inf 0x7fffffff16 using namespace std;17 int read(){18     int x=0,f=1;char ch=getchar();19     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}20     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}21     return x*f;22 }23 int a[maxn],q1[maxn],q2[maxn];24 int main()25 {26     std::ios::sync_with_stdio(false);//cout<<setiosflags(ios::fixed)<<setprecision(1)<<y;27     #ifdef LOCAL28     freopen("data.in","r",stdin);29     freopen("data.out","w",stdout);30     #endif31     int n,m,k;32     cin>>n>>k;33     F(i,1,n)34     {35         cin>>a[i];36     }37     int head=1,tail=0;38     F(i,1,n)39     {40         while(head<=tail&&a[i]<=a[q1[tail]]) tail--;41         q1[++tail]=i;42         while(head<=tail&&q1[tail]-q1[head]>=k) head++;43         if(i>=k) cout<<a[q1[head]]<<" ";44     }45     cout<<endl;46     head=1,tail=0;47     F(i,1,n)48     {49         while(head<=tail&&a[i]>=a[q2[tail]]) tail--;50         q2[++tail]=i;51         while(head<=tail&&q2[tail]-q2[head]>=k) head++;52         if(i>=k) cout<<a[q2[head]]<<" ";53     }54     return 0;55 }
poj 2823

 

0 0
原创粉丝点击