您的位置:首页 > 其它

poj 2823 Sliding Window

2015-12-26 11:12 232 查看
Time Limit: 12000MS   Memory Limit: 65536K
Total Submissions: 50107   Accepted: 14438
Case 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  -1 3
 1 [3  -1  -3] 5  3  6  7  -3 3
 1  3 [-1  -3  5] 3  6  7  -3 5
 1  3  -1 [-3  5  3] 6  7  -3 5
 1  3  -1  -3 [5  3  6] 7  3 6
 1  3  -1  -3  5 [3  6  7] 3 7

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 3
1 3 -1 -3 5 3 6 7

Sample Output

-1 -3 -3 -3 3 3
3 3 5 5 6 7

Source

POJ Monthly--2006.04.28, Ikki

题意:给定长度为N的序列,要求:a[i]~a[i+K-1]中的最小值和最大值

题解:若求最大值,则维护单调队列的递减,用i来计算MAX[i-K+1],也就是Q[head],注意head要>=i-K+1。最小值类似。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
typedef long long LL;
const int maxn=1000010;
int a[maxn],N,K;
int q[maxn],pos[maxn],h,t,now;
int MAX[maxn],MIN[maxn];
inline void getmax(){
h=t=1; q[1]=a[1],pos[1]=1;
for(int i=2;i<=K-1;i++){
while(h<=t&&a[i]>=q[t]) t--;
q[++t]=a[i]; pos[t]=i;
}
for(int i=K;i<=N;i++){
while(h<=t&&a[i]>=q[t]) t--;
q[++t]=a[i]; pos[t]=i;
while(pos[h]<i-K+1) h++;
MAX[i-K+1]=q[h];
}
}
inline void getmin(){
memset(q,0,sizeof(q)); memset(pos,0,sizeof(pos));
h=t=1; q[1]=a[1],pos[1]=1;
for(int i=1;i<=K-1;i++){
while(h<=t&&a[i]<=q[t]) t--;
q[++t]=a[i]; pos[t]=i;
}
for(int i=K;i<=N;i++){
while(h<=t&&a[i]<=q[t]) t--;
q[++t]=a[i]; pos[t]=i;
while(pos[h]<i-K+1) h++;
MIN[i-K+1]=q[h];
}
}
int main(){
scanf("%d%d",&N,&K);
for(int i=1;i<=N;i++) scanf("%d",&a[i]);
getmax();
getmin();
for(int i=1;i<=N-K+1;i++) printf("%d ",MIN[i]);
printf("\n");
for(int i=1;i<=N-K+1;i++) printf("%d ",MAX[i]);
return 0;
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: