
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.
题目
- 原题地址:Sliding Window
- 题目编号:NC51001
- 题目类型:单调队列
- 时间限制:C/C++ 1秒,其他语言2秒
- 空间限制:C/C++ 32768K,其他语言65536K
1.题目大意
- 一个长为
n的数组,现有长为k的滑动窗口,从头到尾依次移动,求每次滑动窗口中的最大值和最小值
2.题目分析
3.题目代码
#include <bits/stdc++.h>
using namespace std;
#define N 1000006
int n, k, a[N], id[N], l, r, b[N];
int main() {
cin >> n >> k;
for (int i=1;i<=n;i++) cin >> a[i];
l = 1, r = 0;
for (int i=1;i<=n;i++) {
while (r>=l&&a[i]<b[r]) r--;//队中有元素,并且队尾元素比当前元素大,队尾元素出队
b[++r] = a[i]; //当前元素入队
id[r] = i; //记录队尾元素对应的下标
if (i-id[l]+1>k) l++; //如果不在窗口内就右移队首下标
if (i>=k) cout << b[l] << " ";//处理好第一个窗口内的所有元素再开始输出
}
cout << endl;
l = 1, r = 0;
memset(id, 0, sizeof(id)); memset(b, 0, sizeof(b));
for (int i=1;i<=n;i++) {
while (r>=l&&a[i]>b[r]) r--;
b[++r] = a[i];
id[r] = i;
if (i-id[l]+1>k) l++;
if (i>=k) cout << b[l] << " ";
}
return 0;
}