POJ2823 (monotone queue)

 

POJ2823

Meaning of the questions: give n digits, there is a size k box, digital box from left to right, a total frame n-k + 1 times, each time asking digital box minimum and maximum values.

Ideas: first thought may be just the maximum, because the number 1e6, maintenance complexity of the biggest heap is nlogn, certainly timed out. We can think of, every frame is moved one space to the right, a number will only increase, decrease a number, you can think of, we have to maintain a sequence,

Through this sequence to update the maximum value of erasure left out, this may be thought to use to solve the monotonous queue, we maintain a monotonically decreasing sequence, each newly added digital If the minimum, put the tail, if greater, to delete the tail element in turn, find it in this position. By this way, we make a queue, always has the current maximum.

In summary, for selecting the maximum value, maintains a descending sequence, minimum, maintains an ascending sequence.

 

 

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
struct note
{
    int x,y;
} q[maxn];

int minn[maxn],maxx[maxn];
int a[maxn];
int n,k;
void getmax()
{
    int head=1;
    int tail=0;
    for(int i=1; i<=k-1; i++)
    {
        while(q[tail].x<=a[i]&&head<=tail)
        {
            tail--;
        }
        q[++tail].x=a[i];
        q[tail].y=i;
    }
    for(int i=k; i<=n; i++)
    {
        while(q[tail].x<=a[i]&&head<=tail)
        {
            tail--;
        }
        q[++tail].x=a[i];
        q[tail].y=i;
        while(q[head].y<(i-k+1))
        {
            head++;
        }
        maxx[i-k+1]=q[head].x;
    }
}

void getmin()
{
    int head=1;
    int tail=0;
    for(int i=1;i<=k-1;i++)
    {
        while(a[i]<=q[tail].x&&head<=tail)
        {
            tail--;
        }
        q[++tail].x=a[i];q[tail].y=i;
    }
    for(int i=k;i<=n;i++)
    {
        while(a[i]<=q[tail].x&&head<=tail)
        {
            tail--;
        }
        q[++tail].x=a[i];q[tail].y=i;
        while(q[head].y<(i-k+1))
        {
            head++;
        }
        minn[i-k+1]=q[head].x;
    }
}
int main()
{

    scanf("%d%d",&n,&k);
    for(int i=1; i<=n; i++)
        scanf("%d",&a[i]);
    getmax();
    getmin();
    for(int i=1; i<=n-k+1; i++)
        printf("%d ",minn[i]);
    printf("\n");
    for(int i=1;i<=n-k+1;i++)
        printf("%d ",maxx[i]);
}

 

Guess you like

Origin www.cnblogs.com/dongdong25800/p/11112630.html