poj-2823 (monotonic queue)

The meaning of the question: give you an array of length n, ask the maximum value of each segment of length m;

Problem-solving ideas: This problem is an introductory question for monotonic queues;

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#define maxn 1000100
using namespace std;
struct node
{
    int val;
    int pos;
} a [maxn];
int que[maxn];
int mn[maxn];
int mx[maxn];
int n,m;
int s[maxn];
void get_min()
{
    int head=1,tail=0,i;
    for(i=1;i<m;i++)
    {
        while(head<=tail&&a[tail].val>=s[i])
            tail--;
        a[++tail].val=s[i];
        a[tail].pos=i;
    }
    for(;i<=n;i++)
    {
        while(head<=tail&&a[tail].val>=s[i])
            tail--;
        a[++tail].val=s[i];
        a[tail].pos=i;
        while(a[head].pos<i-m+1)
            head++;
        mn[i-m+1]=a[head].val;
    }
}
void get_max()
{
    int head=1,tail=0,i;
    for(i=1;i<m;i++)
    {
        while(head<=tail&&a[tail].val<=s[i])
            tail--;
        a[++tail].val=s[i];
        a[tail].pos=i;
    }
    for(;i<=n;i++)
    {
        while(head<=tail&&a[tail].val<=s[i])
            tail--;
        a[++tail].val=s[i];
        a[tail].pos=i;
        while(a[head].pos<i-m+1)
            head++;
        mx[i-m+1]=a[head].val;
    }
}
intmain()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf("%d",&s[i]);
    get_max();
    get_min();
    for(int i=1;i<=n-m+1;i++)
        printf("%d ",mn[i]);
    printf("\n");
    for(int i=1;i<=n-m+1;i++)
        printf("%d ",mx[i]);
    printf("\n");
    return 0;
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325424925&siteId=291194637