首页 > 代码库 > POJ2823 ·Sliding Window

POJ2823 ·Sliding Window

传送门

 

Sliding Window

 

Time Limit: 12000MS Memory Limit: 65536K
   
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 -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
 
又刷水题了T^T..果果的单调队列。。或者别的数据结构乱搞。。不过线段树什么的能不能过我就不晓得了。。
 1 #include<set> 2 #include<queue> 3 #include<cstdio> 4 #include<cstdlib> 5 #include<cstring> 6 #include<iostream> 7 #include<algorithm> 8 using namespace std; 9 const int N = 1000007;10 #define For(i,n) for(int i=1;i<=n;i++)11 #define Rep(i,l,r) for(int i=l;i<=r;i++)12 13 int n,Loc[N],k,Q[N],A[N]; 14 15 void Max(){    16     int l = 1 ,r = 0;17     For(i,k-1){18         while(l<=r&&Q[r]<=A[i]) r--;19         Q[++r]=A[i];Loc[r]=i;20     }21     Rep(i,k,n){22         while(l<=r&&Q[r]<=A[i]) r--;23         Q[++r]=A[i];Loc[r]=i;24         while(Loc[l]<=i-k) l++;                    25         if(k==n)  printf("%d\n",Q[l]);26         else      printf("%d ",Q[l]);27     } 28 }29 30 void Min(){31     int l = 1 ,r = 0;32     For(i,k-1){33         while(l<=r&&Q[r]>=A[i]) r--;34         Q[++r]=A[i];Loc[r]=i;35     }36     Rep(i,k,n){37         while(l<=r&&Q[r]>=A[i]) r--;38         Q[++r]=A[i];Loc[r]=i;39         while(Loc[l]<=i-k) l++;                   40         if(k==n)  printf("%d\n",Q[l]);41         else      printf("%d ",Q[l]);42     } 43     puts("");44 }45 46 int main(){47     scanf("%d%d",&n,&k);48     For(i,n) scanf("%d",&A[i]);49     Min();Max();50     return 0;51 }

 

 

POJ2823 ·Sliding Window