POJ 2823 Sliding Window 再探单调队列

又涂刷者经典题,感觉跟以前未一致了,变得进一步爱了解了,不上课了,看代码。注意:要为此C++提交,用G++会超时。。

代码:

图片 1图片 2

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define N 1000007

int a[N],mp[N],head,tail,n,k;

inline void pushup(int i)
{
    while(tail > head && a[i] < a[mp[tail-1]])
        tail--;
    mp[tail++] = i;  //mq 
}

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

void solve(int cmd)
{
    head = tail = 0;
    int i;
    void (*push)(int) = cmd?pushdown:pushup;
    for(i=1;i<=k&&i<=n;i++)
        push(i);
    printf("%d",a[mp[head]]);
    for(;i<=n;i++)
    {
        while(head != tail && mp[head] < i-k+1)
            head++;
        push(i);
        printf(" %d",a[mp[head]]);
    }
    printf("\n");
}

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

View Code