poj2823_单调队列简单入门

题目链接:http://poj.org/problem?id=2823

#include<iostream>

#include<cstdio>

#define M 1000001

using namespace std;



int n,k;

int a[M];

int q[M];

int p[M];



void get_min()

{

    int head=1;

    int tail=0;

    for(int i=0;i<k-1;i++)

    {

        while(head<=tail&&a[i]<=q[tail])

            --tail;

        q[++tail]=a[i];

        p[tail]=i;

    }

    for(int i=k-1;i<n;i++)

    {

        while(head<=tail&&a[i]<=q[tail])

            --tail;

        q[++tail]=a[i];

        p[tail]=i;

        while(p[head]<i-k+1)

        {

            ++head;

        }

        cout<<q[head]<<" ";

    }

    cout<<endl;

}



void get_max()

{

    int head=1;

    int tail=0;

    for(int i=0;i<k-1;i++)

    {

        while(head<=tail&&a[i]>=q[tail])

            --tail;

        q[++tail]=a[i];

        p[tail]=i;

    }

    for(int i=k-1;i<n;i++)

    {

        while(head<=tail&&a[i]>=q[tail])

            --tail;

        q[++tail]=a[i];

        p[tail]=i;

        while(p[head]<i-k+1)

        {

            ++head;

        }

        cout<<q[head]<<" ";

    }

    cout<<endl;

}



int main()

{

    //freopen("d:\\test.txt","r",stdin);

    scanf("%d%d",&n,&k);

    for(int i=0;i<n;i++)

    {

        scanf("%d",&a[i]);

    }

    get_min();

    get_max();

    return 0;

}

 

你可能感兴趣的:(poj)