POJ 2823 Sliding Window 再探单调队列

重新刷这个经典题,感觉跟以前不一样了,变得更加容易理解了,不讲解了,看代码。注意:要用C++提交,用G++会超时。。

代码:

POJ 2823 Sliding Window 再探单调队列
#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

POJ 2823 Sliding Window 再探单调队列,布布扣,bubuko.com

POJ 2823 Sliding Window 再探单调队列

上一篇:Ubuntu常用命令大全


下一篇:关于老驱动不能在windows 8下正常安装的问题