POJ 2823 Sliding Window(单调队列学习)

Sliding Window

Time Limit: 12000MS   Memory Limit: 65536K
Total Submissions: 78269   Accepted: 22148
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 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

  思路: 单调队列, 但是队列中存储的是单调元素的下标,因为是大小为K的滑动窗口。

             建议用C++ 交 ,否则会超时。

 

#include
#include
using namespace std;
const int maxn = 1e6+7; 
int num[maxn],maxx[maxn],minn[maxn],queue1[maxn],queue2[maxn];
int main(void){
    int i,n,front1,front2,tail1,tail2,cnt,k;
    scanf("%d%d",&n,&k);
    cnt=front1=front2=tail1=tail2=1;
      for(i=1;i<=n;i++) {
      scanf("%d",&num[i]);
      if( i- queue1[front1] >=k )
          front1++;
      if( i - queue2[front2] >=k)
          front2++;
      if( num[i] >= num[ queue1[tail1] ] )
          while( num[i] >= num[queue1[tail1]] && tail1 >= front1)
                 tail1--;
      
      queue1[++tail1] = i;
      if( num[i] <= queue2[tail2])
         while(num[i] <= num[queue2[tail2]]&& tail2>=front2)
      tail2--;
      queue2[++tail2] = i;     
      if( i >= k) {
          maxx[cnt] = num[queue1[front1]];
          minn[cnt++] =num[queue2[front2]];
       }
   }
   for( i= 1;i

 

你可能感兴趣的:(个人修行)