Sliding Window
Time Limit: 12000MS | Memory Limit: 65536K | |
Total Submissions: 30999 | Accepted: 9242 | |
Case Time Limit: 5000MS |
Description
An array of size
n ≤ 10
6 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.
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
Window position | Minimum value | Maximum 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
题意:求由某一个数开始连续k个数最小值
题解:dp【i】【j】表示第 j 个数开始连续(1<<i) 个数的最大(小)值,则有转移方程 dp2[flag][j]=MIN(dp2[!flag][j],dp2[!flag][j+(1<<(i-1))]); 若直接开20*100W的数组会爆内存,所以只能滚动了....
#include<stdio.h>
#include<math.h>
int a[1000005];
int dp2[2][1000005];
int MIN(int a,int b){ return a<b?a:b; }
int MAX(int a,int b){ return a>b?a:b; }
int main()
{
int n,N,k,K,i,j,flag;
while(scanf("%d%d",&n,&k)>0)
{
for(i=0;i<n;i++)
{
scanf("%d",a+i);
dp2[0][i]=a[i];
}
N=n-k;
K=log(k*1.0)/log(2.0);
for(flag=i=1;i<=K;i++)
{
for(j=0;j+(1<<i)-1<n;j++)
dp2[flag][j]=MIN(dp2[!flag][j],dp2[!flag][j+(1<<(i-1))]);
if(i!=K) flag=!flag;
}
for(i=0;i<N;i++) printf("%d ",MIN(dp2[flag][i],dp2[flag][i+k-(1<<(K))]));
printf("%d\n",MIN(dp2[flag][i],dp2[flag][i+k-(1<<(K))]));
for(i=0;i<n;i++) dp2[0][i]=a[i];
for(flag=i=1;i<=K;i++)
{
for(j=0;j+(1<<i)-1<n;j++)
dp2[flag][j]=MAX(dp2[!flag][j],dp2[!flag][j+(1<<(i-1))]);
if(i!=K) flag=!flag;
}
for(i=0;i<N;i++) printf("%d ",MAX(dp2[flag][i],dp2[flag][i+k-(1<<(K))]));
printf("%d\n",MAX(dp2[flag][i],dp2[flag][i+k-(1<<(K))]));
}
return 0;
}