P1440 求m区间内的最小值 (单调队列)
求m区间内的最小值
题目描述
一个含有 \(n\) 项的数列,求出每一项前的 \(m\) 个数到它这个区间内的最小值。若前面的数不足 \(m\) 项则从第 \(1\) 个数开始,若前面没有数则输出 \(0\)。
输入格式
第一行两个整数,分别表示 \(n\),\(m\)。
第二行,\(n\) 个正整数,为所给定的数列 \(a_i\)。
输出格式
\(n\) 行,每行一个整数,第 \(i\) 个数为序列中 \(a_i\) 之前 \(m\) 个数的最小值。
样例 #1
样例输入 #1
6 2
7 8 1 4 3 2
样例输出 #1
0
7
7
1
1
3
提示
对于 \(100\%\) 的数据,保证 \(1\le m\le n\le2\times10^6\),\(1\le a_i\le3\times10^7\)。
解析
(日常切水题)和窗口差不多,初始时设h=1,t=0。然后套模板
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
int n, m, a[N];
int q[N], h, t, ans[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i ++) cin >> a[i];
h = 1, t = 0;
for (int i = 1; i <= n; i ++) {
while (h <= t && a[i] < a[q[t]]) t --;
q[++ t] = i;
while (h <= t && i - q[h] + 1 > m) h ++;
ans[i + 1] = a[q[h]];
}
for (int i = 1; i <= n; i ++) cout << ans[i] << '\n';
return 0;
}