Description
An array of size n ≤ 10 6 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 31 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 33 3 5 5 6 7
这道题很明显用单调队列。每到一个新的区间,都判断当前队列的首位是否已不在这个区间,如果不在,就把队首出队。加入新元素。每加入一个元素,都从队列尾往前遍历,如果当前结单大于或小于(要写两个队列)要放进的结点,就从后面把这个元素出队。这个操作比较骚,所以我们写出来的东西不是严谨的队列,而是一个有栈性质的队列。这就有点骚了,所以我们必须手写一个这样的奇怪的玩意。
第一次的提交的时候tle了,看来poj对我的恶意不小啊。然后抱着侥幸心理加了一个读优,然后就AC了,23333。
不多bb我放代码了,arr存数组,有两个队列max_queue和min queue对应max tail等。
#include#include #include using namespace std;int arr[1000000];int max_queue[1000000], min_queue[1000000], max_tail, min_tail, max_head = 1, min_head = 1;int N, K;inline int read(){ int X = 0, w = 0; char ch = 0; while (!isdigit(ch)) { w |= ch == '-'; ch = getchar(); } while (isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar(); return w ? -X : X;}bool max_empty(){ if (max_tail == max_head - 1) return true; else return false;}bool min_empty(){ if (min_tail == min_head - 1) return true; else return false;}void min_push(int a){ //if(!min_empty()) while (arr[a] <= arr[min_queue[min_tail]] && !min_empty()) min_tail--; min_tail++; min_queue[min_tail] = a;}void max_push(int a){ while (arr[a] > arr[max_queue[max_tail]] && !max_empty()) max_tail--; max_tail++; max_queue[max_tail] = a;}int min_top(){ return min_queue[min_head];}int max_top(){ return max_queue[max_head];}void min_pop(){ min_head++;}void max_pop(){ max_head++;}int main(){ cin >> N >> K; for (int i = 1; i <= N; i++) { arr[i]=read(); } for (int i = 1; i <= K; i++) { min_push(i); } cout << arr[min_top()] << " "; for (int i = 1; i <= N - K; i++) { if (min_top() == i) min_pop(); min_push(i + K); cout << arr[min_top()] << " "; } cout << endl; for (int i = 1; i <= K; i++) { max_push(i); } cout << arr[max_top()] << " "; for (int i = 1; i <= N - K; i++) { //cout<<"max "< <<" "; if (max_top() == i) max_pop(); max_push(i + K); cout << arr[max_top()] << " "; } //system("pause");}