Sliding Window POJ - 2823

 

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
 1 #include <cstdio>
 2 #include <vector>
 3 #include <cstring>
 4 using namespace std;
 5 const int MAXN=1e6+10;
 6 int Q[MAXN],a[MAXN];
 7 vector<int>MAX;
 8 vector<int>MIN;
 9 int n,m;
10 void get_MIN()
11 {
12     int head=1,tail=1;
13     Q[tail]=1;
14     for (int i = 1; i <=n ; ++i) {
15         while(head<=tail&&a[i]<a[Q[tail]]) tail--;
16         Q[++tail]=i;
17         while(head<=tail&&Q[head]<i-m+1) head++;
18         if(i>=m)
19         MIN.push_back(a[Q[head]]);
20     }
21 }
22 
23 void get_MAX()
24 {
25     int head,tail;
26     head=1;tail=1;
27     Q[tail]=1;
28     for (int i = 1; i <=n ; ++i) {
29         while(head<=tail&&a[i]>a[Q[tail]]) tail--;
30         Q[++tail]=i;
31         while(head<=tail&&Q[head]<i-m+1)
32             head++;
33         if(i>=m)
34         MAX.push_back(a[Q[head]]);
35     }
36 }
37 
38 int main()
39 {
40     scanf("%d%d",&n,&M);
41     for (int i = 1; i <=n ; ++i) {
42         scanf("%d",&a[i]);
43     }
44     get_MIN();
45     for (int i = 0; i <MIN.size() ; ++i) {
46         printf("%d ",MIN[i]);
47     }
48     printf("\n");
49     get_MAX();
50     memset(Q,0, sizeof(Q));
51     for (int i = 0; i <MAX.size() ; ++i) {
52         printf("%d ",MAX[i]);
53 
54     }
55     printf("\n");
56     return 0;
57 }
View Code

 

posted @ 2018-07-31 10:49  岩扉  阅读(208)  评论(0编辑  收藏  举报