正常状态定义
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5+5;
#define LL long long
#define pb push_back
#define F(i,a,b) for(int i=a;i<=b;i++)
int n,k,a[N],q[N],st = 1,ed = 1;
LL f[N],s[N];
/*
f[i]表示在前i头牛中选的最大效率
i-k<=j<=i-1
1.不选 f[i] = f[i-1]
2.选 f[i] = f[j-1]+s[i]-s[j]
*/
LL calc(int i){ return f[i-1]-s[i];}
int main()
{
cin>>n>>k;
F(i,1,n) cin>>a[i],s[i] = s[i-1]+a[i];
F(i,1,n)
{
f[i] = f[i-1];
while(st <= ed && q[st] < i-k) st++;
if(st <= ed) f[i] = max(f[i],calc(q[st])+s[i]);
while(st <= ed && calc(q[ed]) <= calc(i)) ed--;
q[++ed] = i;
}
cout << f[n] << '\n';
return 0;
}
新型的状态定义
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5+5;
#define LL long long
#define pb push_back
#define F(i,a,b) for(int i=a;i<=b;i++)
int n,k,a[N],q[N],st = 1,ed = 1;
LL f[N],s[N];
/*
f[i]表示前i头牛,不选第i头牛的最大效率
i-k-1<=j<=i-1
f[i] = max(f[i],f[j]+s[i-1]-s[j])
f[i] = max{f[j]-s[j]+s[i-1]} i-k-1<=j<=i-1
*/
LL calc(int i){ return f[i]-s[i];}
int main()
{
cin>>n>>k;
F(i,1,n) cin>>a[i],s[i] = s[i-1]+a[i];
q[1] = 0;
F(i,1,n+1)
{
while(st <= ed && q[st] < i-k-1) st++;
if(st <= ed) f[i] = max(f[i],calc(q[st])+s[i-1]);
while(st <= ed && calc(q[ed]) <= calc(i)) ed--;
q[++ed] = i;
}
cout << f[n+1] << '\n';
return 0;
}