/*
题目描述:给出n(n <= 1e6)个数的数组a和一个整数k,定义b[i]为a[i],a[i + 1],...,a[i + k - 1]当中的最小值,c[i]为
a[i],a[i + 1],...,a[i + k - 1]当中的最大值,要求输出数组b、c
方法:使用单调队列解决,首先求c,维护一个单减的队列q,再维护一个队列p,p中元素是q中元素对应的序号。
当加入一个元素a[i]每次从队尾入队一个元素,如果该元素大于等于队尾元素,就将队尾元素弹出,一直弹
到队尾元素大于当前元素或队列为空时,将该元素加入队列。这时通过p队列看队首元素在a中的位置,如果
其在a中的位置pos<i - k + 1,那么将队首元素弹出。此时q中队首即为c[i - k + 1]
*/
#pragma warning(disable:4786)
#pragma comment(linker, "/STACK:102400000,102400000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<string>
#include<sstream>
#include<bitset>
#define LL long long
#define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define lson l,m,x<<1
#define rson m+1,r,x<<1|1
using namespace std;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int maxn = 1e6 + 5;
int a[maxn], b[maxn], c[maxn], q[maxn], p[maxn];
void print(int * a, int n , int k)
{
for (int i = 1; i <= n - k + 1; i++){
if (i != n - k + 1) printf("%d ", a[i]);
else printf("%d\n", a[i]);
}
return;
}
int main()
{
int n, k;
while (scanf("%d%d", &n, &k) != EOF){
int head, tail;
head = tail = 0;
for (int i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
for (int i = 1; i <= n; i++){
while (head < tail && q[tail - 1] <= a[i]){
--tail;
}
q[tail] = a[i];
p[tail] = i;
++tail;
if (i >= k){
while (head < tail && p[head] <= i - k){
++head;
}
c[i - k + 1] = q[head];
}
}
head = tail = 0;
for (int i = 1; i <= n; i++){
while (head < tail && q[tail - 1] >= a[i]){
--tail;
}
q[tail] = a[i];
p[tail] = i;
++tail;
if (i >= k){
while (head < tail && p[head] <= i - k){
++head;
}
b[i - k + 1] = q[head];
}
}
print(b, n , k);
print(c, n , k);
}
return 0;
}
POJ 2823 Sliding Window
最新推荐文章于 2021-01-25 20:02:52 发布