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
[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 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个结点快速排序k* logk,每个点扫描一遍n,因此时间复杂度n* k* logk.用单调队列的思想:入队出队一次操作,时间复杂度是o(n)级别的。
这道题几点坑爹和坑自己的地方在于:
1.输出格式,空格,回车。
2.哦,对,还有一个坑爹的地方是使用g++就tle,C++就ac.
3.for循环要从1开始,原始是如果滑动窗口只有一个数,即k=1,那么for从2开始循环,就会把第一个数覆盖。
/*8 3
1 3 -1 -3 5 3 6 7
-1 -3 -3 -3 3 3
3 3 5 5 6 7*/
//边界和等于
#include<iostream>
#include<cstdio>
using namespace std;
int q[1000005],n,k,a[1000005];
void mn()
{
int head,tail;
head=1,tail=1;//
q[tail]=1;
for(int i=1;i<=n;i++)
{
while(a[i]<a[q[tail]] && head<=tail)
tail--;
q[++tail]=i;
while(q[tail]-q[head]+1>k && head<=tail)
head++;
if(i>=k)
printf("%d ",a[q[head]]);
}
printf("\n");
}
void mx()
{
int head,tail;
head=1,tail=1;//
q[1]=1;
for(int i=1;i<=n;i++)
{
while(a[i]>a[q[tail]] && head<=tail)
tail--;
q[++tail]=i;
while(q[tail]-q[head]+1>k && head<=tail)
head++;
if(i>=k)//脑残错误:应该>=,但=
printf("%d ",a[q[head]]);
}
printf("\n");
}
int main()
{
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
mn();
mx();
return 0;
}