Sol
一个很显然的暴力,设\(f[i]\)表示选到\(i\)的最优效率
每次枚举一段不与前面连续的长度小于\(k\)的区间转移来
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1e5 + 5);
IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}
int n, k;
ll f[_], sum[_];
int main(RG int argc, RG char* argv[]){
n = Input(); k = Input();
for(RG int i = 1; i <= n; ++i) f[i] = Input(), sum[i] = sum[i - 1] + f[i];
for(RG int i = 2; i <= n; ++i)
for(RG int j = max(0, i - k); j < i; ++j)
f[i] = max(f[i], f[j - 1] + sum[i] - sum[j]);
printf("%lld\n", f[n]);
return 0;
}
把转移中的\(f[j-1]\)和\(sum[j]\)写在一起就可以单调队列优化
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1e5 + 5);
IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}
int n, k;
ll f[_], g[_], sum[_], Q[_], head, tail = 1;
int main(RG int argc, RG char* argv[]){
n = Input(); k = Input();
for(RG int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + Input();
Q[0] = -1; g[0] -= sum[1];
for(RG int i = 1; i <= n; ++i){
while(i - Q[head] - 1 > k) ++head;
f[i] = (Q[head] == -1 ? 0 : g[Q[head]]) + sum[i], g[i] = f[i] - sum[i + 1];
while(head <= tail && g[Q[tail]] < g[i]) --tail;
Q[++tail] = i;
}
printf("%lld\n", f[n]);
return 0;
}