码迷,mamicode.com
首页 > Windows程序 > 详细

POJ 2823 Sliding Window

时间:2015-08-17 23:23:57      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

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

 
解题:单调队列
 
技术分享
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 const int maxn = 1000010;
 6 int d[maxn],q[maxn],hd,tl,n,k;
 7 bool getMin(int a,int b) {
 8     return a <= b;
 9 }
10 bool getMax(int a,int b) {
11     return a >= b;
12 }
13 void solve(bool (*f)(int,int)) {
14     hd = tl = 0;
15     bool flag = false;
16     for(int i = 0; i < n; ++i) {
17         while(hd < tl && f(d[i],q[tl-1])) --tl;
18         q[tl++] = i;
19         if(i + 1 >= k) {
20             while(hd < tl && i - q[hd] + 1 > k) ++hd;
21             if(flag) putchar( );
22             printf("%d",d[q[hd]]);
23             flag = true;
24         }
25     }
26     putchar(\n);
27 }
28 int main() {
29     while(~scanf("%d%d",&n,&k)) {
30         for(int i = 0; i < n; ++i)
31             scanf("%d",d+i);
32         solve(getMin);
33         solve(getMax);
34     }
35     return 0;
36 }
View Code

 

POJ 2823 Sliding Window

标签:

原文地址:http://www.cnblogs.com/crackpotisback/p/4738009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!