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

POJ 2823 Sliding Window(經典單調佇列)

An array of size n ≤ 10 6 is given to you. There is a sliding window of size kwhich 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

 【題意】有一個數列n,顯示寬度為k,數列從顯示屏上滾過(沒錯,就是滾過),求每時刻顯示屏上k個數中的最小值和最大值。

 【分析】 這題是經典的單調佇列模擬題,在每次進來一個數時,和它的前一個數比較,比它大(小),就把前一個數彈出去,繼續向前比較,直到遇到比它小(大)的數,就把它放在這個數後面,因為彈出去的數比後面的數小,所以任何時候螢幕上包含這個數時,這個數都不可能成為最大(最小)數,所以刪掉也就無所謂了。所以這樣執行下去每次隊首的元素就是要求的那個最大(最小)值,輸出即可。

 這裡面是我自己手寫的佇列;

 用時5407ms;

 參考部落格:http://blog.csdn.net/code_pang/article/details/14104487

 【程式碼】:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N=1e6+5;

int str[N];
int head;
int tail;

int a[N];
int n;
int k;

void push_min(int i)
{
    while(tail>head && a[i]<a[str[tail-1]])
        tail--;
    str[tail++]=i;
}

void push_max(int i)
{
    while(tail>head && a[i]>a[str[tail-1]])
        tail--;
    str[tail++]=i;
}

bool isempty(void)
{
    return head==tail;
}

void pop(void)
{
    head++;
}

int Front(void)
{
    return str[head];//注意了,不是直接返回Head
}

void Get_max()
{
    head=tail=0;

    int i;
    for(i=1;i<=k&& i<=n;i++)
    {
        push_max(i);
    }
    printf("%d",a[Front()]);

    for(;i<=n;i++)
    {
        while(!isempty() && Front()+k <=i)
        {
            pop();
        }
        push_max(i);
        printf(" %d",a[Front()]);
    }
    printf("\n");
}

void Get_min()
{
    head=tail=0;
    int i;
    for(i=1;i<=k && i<=n;i++)
        push_min(i);
    printf("%d",a[Front()]);

    for(;i<=n;i++)
    {
        while(!isempty() && Front()+k <=i)
            pop();
        push_min(i);
        printf(" %d",a[Front()]);
    }
    printf("\n");
}

int main()
{
    while(~scanf("%d%d",&n,&k))
    {
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        Get_min();
        Get_max();
    }
    return 0;
}