1. 程式人生 > >POJ 2823 Sliding Window(單調佇列)

POJ 2823 Sliding Window(單調佇列)

題意  長度為n的陣列上有個長度為k的滑窗從左向右移動  求每次移動後滑窗區間的最小值和最大值  輸出兩行  第一行所有最小值  第二行所有最大值

可以用線段樹來做  但是單調佇列更簡單 

單調遞增佇列: 隊尾單調入隊(入隊元素大於隊尾元素時直接入隊  否則隊尾出隊直到隊尾元素小於入隊元素或者佇列為空)  隊首隊尾都可以出隊

求最小值時 先判斷隊首元素是否在滑窗之內  不在隊首就出隊  然後隊首元素就是滑窗中的最小值了   求最大值用單減佇列就行了

#include <cstdio>
using namespace std;
const int N = 1e6 + 5;
int a[N], q[N], t[N];
int front, rear, n, k;

#define NOTMONO (!op && a[i] < q[rear - 1]) || (op && a[i] > q[rear - 1])
void getMonoQueue(int op) //op = 0 時單增佇列  op = 1 時單減佇列
{
    front = rear = 0;
    for(int i = 0; i < n; ++i)
    {
        while( rear > front && (NOTMONO)) --rear;
        t[rear] = i;      //記錄滑窗滑到i點的時間
        q[rear++] = a[i];
        while(t[front] <= i - k) ++front;  //保證隊首元素在滑窗之內
        if(i > k - 2)
            printf("%d%c", q[front], i == n - 1 ? '\n' : ' ');
    }
}

int main()
{
    while (~scanf("%d%d", &n, &k))
    {
        for(int i = 0; i < n; ++i)
            scanf("%d", &a[i]);
        getMonoQueue(0); //單增佇列維護最小值
        getMonoQueue(1); //單減佇列維護最大值
    }

    return 0;
}

//Last modified :   2015-07-06 12:16
Sliding Window

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