题目链接:http://poj.org/problem?id=2823
Sliding Window
Time Limit: 12000MS | Memory Limit: 65536K | |
Total Submissions: 53489 | Accepted: 15337 | |
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.
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
Source
POJ Monthly--2006.04.28, Ikki
思路:维护两个优先队列,一个存储从大到小排序的数的下标(注意是下标),一个存储从小到大排序的数的下标,这样每移动一次,只要从队首找到满足下标差小于k的队首即可,如果不小于,出队列,因为该最大值或者最小值已经不在当前区间内了。详见代码。注意:我的代码要用C++交才能过,G++会超时。
附上AC代码:
思路:维护两个优先队列,一个存储从大到小排序的数的下标(注意是下标),一个存储从小到大排序的数的下标,这样每移动一次,只要从队首找到满足下标差小于k的队首即可,如果不小于,出队列,因为该最大值或者最小值已经不在当前区间内了。详见代码。注意:我的代码要用C++交才能过,G++会超时。
附上AC代码:
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 1000005;
int num[maxn], low[maxn], high[maxn];
int n, k;
struct cmp1{
bool operator () (const int i, const int j){
return num[i] > num[j];
}
};
struct cmp2{
bool operator () (const int i, const int j){
return num[i] < num[j];
}
};
priority_queue<int, vector<int>, cmp1> p;
priority_queue<int, vector<int>, cmp2> q;
int main(){
while (~scanf("%d%d", &n, &k)){
for (int i=0; i<n; ++i)
scanf("%d", num+i);
while (!p.empty())
p.pop();
while (!q.empty())
q.pop();
for (int i=0; i<k; ++i){
p.push(i);
q.push(i);
}
int cnt = 0;
low[cnt] = num[p.top()];
high[cnt++] = num[q.top()];
for (int i=k; i<n; ++i){
p.push(i);
q.push(i);
while (i-p.top() >= k)
p.pop();
while (i-q.top() >= k)
q.pop();
low[cnt] = num[p.top()];
high[cnt++] = num[q.top()];
}
for (int i=0; i<cnt; ++i){
if (i > 0)
printf(" ");
printf("%d", low[i]);
}
printf("\n");
for (int i=0; i<cnt; ++i){
if (i > 0)
printf(" ");
printf("%d", high[i]);
}
printf("\n");
}
return 0;
}