https://www.acwing.com/problem/content/description/1089/
思路
- \(单调对列\ + \ dp\)
\(不能选超过m个连续的数求最大等价于在每m+1个数中选出最小的一个.\)
- \(单调队列中维护的f[i-1,\ i-m-1]区间的最小值\)
- \(需要在队头加入0初始化\)
\(本题与烽火传递是对称的\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
const int N = 1e5 + 7;
int q[N];
int a[N];
ll f[N];
int main() {
IO;
int n, m;
ll sum = 0;
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
sum += a[i];
}
m++;
int hh = 0, tt = 0;
for (int i = 1; i <= n; ++i) {
if (q[hh] < i - m) ++hh;
f[i] = f[q[hh]] + a[i];
while (hh <= tt && f[q[tt]] >= f[i]) --tt;
q[++tt] = i;
}
ll ans = 0;
for (int i = n - m + 1; i <= n; ++i) ans = max(sum - f[i], ans);
cout << ans << '\n';
return 0;
}