Description
An array of size
n ≤ 10
6 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.
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
nintegers 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
题意:有一个区间,维护这个区间的最大值和最小值即可。裸的单调队列,开两个单调队列,分别维护最大值和最小值。没了。
#include<cstdio>
#include<cstring>
#include<algorithm>
#define INF 100000000
#define maxn 2000000
using namespace std;
int num[maxn];
struct WTF {
int k, w;
}q[maxn];
int main()
{
int n, k, end, i,first,flag;
WTF now;
scanf("%d%d", &n, &k);
for (i = 1;i <= n;i++)
{
scanf("%d", &num[i]);
}
///
q[0].k = -INF;
q[0].w = 0;
end = 0;
first = 1;
for (i = 1;i < k;i++)
{
while (num[i] < q[end].k)
{
end--;
}
now.w = i;
now.k = num[i];
q[++end] = now;
}
flag = 0;
for (;i <= n;i++)
{
while (num[i] < q[end].k&&end>=first)
{
end--;
}
now.w = i;
now.k = num[i];
q[++end] = now;
flag++;
while(q[first].w < flag)
first++;
printf("%d", q[first].k);
if (i == n)
printf("\n");
else printf(" ");
}
///
memset(q, 0, sizeof(q));
q[0].k = INF;
q[0].w = 0;
end = 0;
first = 1;
for (i = 1;i < k;i++)
{
while (num[i] > q[end].k)
{
end--;
}
now.w = i;
now.k = num[i];
q[++end] = now;
}
flag = 0;
for (;i <= n;i++)
{
while (num[i] > q[end].k&&first<=end)
{
end--;
}
now.w = i;
now.k = num[i];
q[++end] = now;
flag++;
while (q[first].w < flag)
first++;
printf("%d", q[first].k);
if (i == n)
printf("\n");
else printf(" ");
}
}