POJ 2823 Sliding Window

Sliding Window

Time Limit: 12000ms
Memory Limit: 65536KB
This problem will be judged on PKU. Original ID: 2823
64-bit integer IO format: %lld      Java class name: Main
 
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.
 
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

 
解题:单调队列,太JB卡时间了,需要使用MS C++提交
 
 1 #include <cstdio>
 2 #include <cctype>
 3 using namespace std;
 4 const int maxn = 2000010;
 5 int n,k,d[maxn],q[maxn<<1];
 6 inline bool xiao(int a,int b) {
 7     return a <= b;
 8 }
 9 inline bool da(int a,int b) {
10     return a >= b;
11 }
12 inline bool scan_d(int &num) {
13     bool IsN = false;
14     char in = getchar();
15     if(in == EOF) return false;
16     while(in != '-' && !isdigit(in)) in = getchar();
17     if(in == '-') {
18         IsN = true;
19         num = 0;
20     } else num = in - '0';
21     while((in = getchar()) && isdigit(in)) num = num*10 + in - '0';
22     if(IsN) num = -num;
23     return true;
24 }
25 void solve(bool (*f)(int,int)) {
26     int hd = 0,tl = 0;
27     for(int i = 0; i < n; ++i) {
28         while(hd < tl && q[hd] + k - 1 < i) hd++;
29         while(hd < tl && f(d[i],d[q[tl-1]])) tl--;
30         q[tl++] = i;
31         if(i + 1 >= k) printf("%d%c",d[q[hd]],i + 1 == n?'
':' ');
32     }
33 }
34 int main() {
35     scanf("%d%d",&n,&k);
36     for(int i = 0; i < n; ++i)
37         scan_d(d[i]);
38     solve(xiao);
39     solve(da);
40     return 0;
41 }
View Code
原文地址:https://www.cnblogs.com/crackpotisback/p/4738009.html