G - Sliding Window (单调队列)

https://vjudge.net/contest/283317#problem/G

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 knumbers 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

题意:有N个数,每次从左到右选取k个数,第一行选取每个区间中的最小值输出,第二行选取最大值并输出。

题目分析:参考:https://blog.csdn.net/cokomowang/article/details/38662291

 具体的操作是:从加入第k个数开始,每插入做一次队列单调性更新(删队尾【单调性】,入队,删队首【下标范围k以内】,输出队首【即最值】)

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include<stack>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
const int N=1e6+5;
int n,k,a[N];
struct node{
	int k,num;
}q[N];
void minn()
{
	memset(q,0,sizeof(q));
	q[0].k=-INF;
	int l=1,r=1;
	for(int i=1;i<=k;i++){
		while(a[i]<=q[r].k&&l<=r)r--;
		q[++r].k=a[i];
		q[r].num=i;
	}
	for(int i=k;i<=n;i++){
		while(a[i]<=q[r].k&&l<=r)r--;
		q[++r].k=a[i];
		q[r].num=i;
		while(q[l].num<i-k+1)l++;
		printf("%d ",q[l].k);
	}
}
void maxx()
{
	memset(q,0,sizeof(q));
	q[0].k=INF;
	int l=1,r=1;
	for(int i=1;i<=k;i++){
		while(a[i]>=q[r].k&&l<=r)r--;
		q[++r].k=a[i];
		q[r].num=i;
	}
	for(int i=k;i<=n;i++){
		while(a[i]>=q[r].k&&l<=r)r--;
		q[++r].k=a[i];
		q[r].num=i;
		while(q[l].num<i-k+1)l++;
		printf("%d ",q[l].k);
	}
}
int main()
{
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++)cin>>a[i];
	minn();
	puts("");
	maxx();
}

猜你喜欢

转载自blog.csdn.net/qq_43490894/article/details/87897237