Sliding Window
Time Limit: 12000MS Memory Limit: 65536K
Total Submissions: 55654 Accepted: 16011
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
Source
POJ Monthly--2006.04.28, Ikki
題意:
有一個n個元素的整數(shù)序列,一個能容納k個元素的滑動窗口花椭,窗口從頭滑至尾,求每一個區(qū)間中的最小數(shù)和最大數(shù)答姥。
思路:
單調(diào)隊列。維護兩個單調(diào)隊列垃喊,分別嚴格單調(diào)增称开、嚴格單調(diào)減,若隊頭元素距離當前元素超過k搓侄,則需出隊,該隊頭元素既是區(qū)間最大/最小话速。
#include<cstdio>
#include<deque>
using namespace std;
const int maxn = 1000000;
struct Node {
int value, pos;
Node(int v = -1, int p = -1) :value(v), pos(p) {};
};
deque<Node> minque;
deque<Node> maxque;
int maxans[maxn + 10];
int minans[maxn + 10];
int main() {
int n, m, th = 0;
int num;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i) {
scanf("%d", &num);
if (i >= m) {
minans[th] = minque.front().value;
maxans[th++] = maxque.front().value;
// 除去不屬于同一區(qū)間的元素
while (!minque.empty() && i - minque.front().pos >= m)
minque.pop_front();
while (!maxque.empty() && i - maxque.front().pos >= m)
maxque.pop_front();
}
// 入隊讶踪,維護隊列單調(diào)
while (!minque.empty() && minque.back().value >= num)
minque.pop_back();
minque.push_back(Node(num, i));
while (!maxque.empty() && maxque.back().value <= num)
maxque.pop_back();
maxque.push_back(Node(num, i));
}
minans[th] = minque.front().value;
maxans[th++] = maxque.front().value;
for (int i = 0; i < th - 1; ++i)
printf("%d ", minans[i]);
printf("%d\n", minans[th - 1]);
for (int i = 0; i < th - 1; ++i)
printf("%d ", maxans[i]);
printf("%d\n", maxans[th - 1]);
return 0;
}