Window Queue monotone

Title Description

Give you an array of length N, a length K of the sliding form from the leftmost number K to the extreme right, you can see the window, each time a form is moved to the right, as follows:

Window  position                Min value   Max value

[1  3  -1]  -3  5  3  6  7      -1            3

1  [3  -1  -3]  5  3  6  7      -3            3

1  3  [-1  -3  5]  3  6  7      -3            5

1  3  -1  [-3  5  3]  6  7      -3            5

1  3  -1  -3  [5  3  6]  7      3             6

1  3  -1  -3  5  [3  6  7]      3             7

Your task is to find a window Max value at each position, Min value.

Input Format

The first line n, k, the second row of the array length n

Output Format

Min value for each position of a first row, a second row position of each of Max value

SAMPLE INPUT

8 3
1 3 -1 -3 5 3 6 7

Sample Output

-1 -3 -3 -3 3 3
3 3 5 5 6 7

Restrictions and conventions

20%:n≤500;

50%:n≤100000;

100%:n≤1000000;

Time limit: 1s

Space limitations: 128MB

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn = 1000000+10;
int a[maxn],ans1[maxn],pos1[maxn],ans2[maxn],pos2[maxn];
int main()
{
    int n,k;
    cin>>n>>k;
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    int l1=0,r1=1,l2=0,r2=0;
    for(int i=1;i<=n;i++)
    {
        if(i-k+1>pos1[l1]) l1++;
        while(a[i]<a[ pos1[r1] ] && r1>=l1) r1--;
        pos1[++r1]=i;
        ans1[i]=a[pos1[l1]];
        
        if(i-k+1>pos2[l2]) l2++;
        while(a[i]>a[ pos2[r2] ] && r2>=l2) r2--;
        pos2[++r2]=i;
        ans2[i]=a[pos2[l2]];
    }
    for(int i=k;i<=n;i++) cout<<ans1[i]<<" ";
    cout<<endl;
    for(int i=k;i<=n;i++) cout<<ans2[i]<<" ";
       /* if(a[i]>a[Max[bx]]) 
            {
                int j;
                for(j=bx;j>=0;j--)
                {
                    if(a[i]<a[Max[j])
                    break;
                }
                bx=j+1;
                Max[bx]=i;
            }
        else Max[++bx]=a[i];
        
        if(a[i]<Min[sx])
            {
                int j;
                for(j=sx;j>=0;j--)
                {
                    if(a[i]>Min[j])
                    break;
                }
                sx=j+1;
                Min[sx]=a[i];
            }
        else Max[++sx]=a[i];
        
        
        
        if(i>=k)
        {
            if(bx-k>0) amax[i]=Max[bx-k];
            else amax[i]=Max[1];
            
            if(sx-k>0) amin[i]=Min[sx-k];
            else amin[i]=Min[1];
        }*/
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/hfang/p/11239923.html