poj 2823 单调队列

思路:裸的单调队列。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define Maxn 1000010
using namespace std;
int n,k,que[Maxn],num[Maxn],head,rear;
int main()
{
    int i,j,a;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        head=1;
        rear=0;
        for(i=1;i<=n;i++)
            scanf("%d",num+i);
        for(i=1;i<=k;i++)
        {
            while(rear>=head&&num[que[rear]]>=num[i])
                rear--;
            que[++rear]=i;
        }
        printf("%d",num[que[head]]);
        for(i=k+1;i<=n;i++)
        {
            if(i-que[head]>=k)
                head++;
             while(rear>=head&&num[que[rear]]>=num[i])
                rear--;
                que[++rear]=i;
                printf(" %d",num[que[head]]);
        }
        printf("\n");
        head=1;
        rear=0;
        for(i=1;i<=k;i++)
        {
            while(rear>=head&&num[que[rear]]<=num[i])
                rear--;
            que[++rear]=i;
        }
        printf("%d",num[que[head]]);
        for(i=k+1;i<=n;i++)
        {
            if(i-que[head]>=k)
                head++;
             while(rear>=head&&num[que[rear]]<=num[i])
                rear--;
                que[++rear]=i;
                printf(" %d",num[que[head]]);
        }
        printf("\n");
    }
    return 0;
}

 

posted @ 2013-08-02 16:21  fangguo  阅读(145)  评论(0编辑  收藏  举报