问题描述:
Description
An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
Window position Minimum value Maximum value
Your task is to determine the maximum and minimum values in the sliding window at each position.
Input
The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line.
Output
There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values.
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
大致题意:
给定一个数组,求长度为k的子序列的最大值最小值。
思路分析:
裸单调队列。
求最大值时,建一个递减的单调队列。求最小值时,建递增的单调队列。
ac代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define N 1000005
int a[N];
int maxx[N];
int minn[N];
int n,m;
void max_slove() //递减的单调队列。
{
//memset(maxx,0,sizeof(maxx));
int i,j,k,l,r;
l=1;r=0;
for(i=0;i<m-1;i++)
{
while(a[i]>=a[maxx[r]] && r>=l)
r--;
r++;
maxx[r]=i;
}
for(i=m-1;i<n;i++)
{
while(a[i]>=a[maxx[r]] && r>=l)
r--;
r++;
maxx[r]=i;
while(maxx[l]<i-m+1)
l++;
if(i==m-1)
cout<<a[maxx[l]];
else
cout<<" "<<a[maxx[l]];
}
}
void min_slove() //递增的单调队列。
{
//memset(minn,0,sizeof(minn));
int i,j,k,l,r;
l=1;r=0;
for(i=0;i<m-1;i++)
{
while(a[i]<=a[minn[r]] && r>=l)
r--;
r++;
minn[r]=i;
}
for(i=m-1;i<n;i++)
{
while(a[i]<=a[minn[r]] && r>=l)
r--;
r++;
minn[r]=i;
while(minn[l]<i-m+1)
l++;
if(i==m-1)
cout<<a[minn[l]];
else
cout<<" "<<a[minn[l]];
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
min_slove();
cout<<endl;
max_slove();
cout<<endl;
return 0;
}