![在这里插入图片描述](https://img-blog.csdnimg.cn/20181103221757349.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyMTEwMzE4,size_16,color_FFFFFF,t_70)
solution
- subtask1 暴力dp O(nk)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
#include<cstdlib>
#include<ctime>
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f;
inline ll read(){
char ch=' ';ll f=1;ll x=0;
while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*f;
}
const ll N=1e5+100;
ll f[N];
ll sum[N];
ll a[N];
int main()
{
freopen("work.in","r",stdin);
freopen("work.out","w",stdout);
ll n,k;
n=read();k=read();
ll i,j;
sum[0]=0;
for(i=1;i<=n;i++)
{
a[i]=read();
sum[i]=sum[i-1]+a[i];
}
f[0]=0;
for(i=1;i<=n+1;i++)
{
for(j=i-1;j>=max((ll)0,i-k-1);j--)
{
f[i]=max(f[i],f[j]+sum[i-1]-sum[j]);
}
}
cout<<f[n+1]<<endl;
return 0;
}
- 我们发现后面那一坨可以用单调队列维护(相当于一个长度为k的滑动窗口)关键字为dp[i]-sum[i] (自己用前缀和减一下就出来了)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20181103223652938.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyMTEwMzE4,size_16,color_FFFFFF,t_70)
code
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
#include<cstdlib>
#include<ctime>
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f;
inline ll read(){
char ch=' ';ll f=1;ll x=0;
while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*f;
}
const ll N=1e5+100;
ll f[N];
ll sum[N];
ll a[N];
ll q[N],h,t;
int main()
{
freopen("work.in","r",stdin);
freopen("work.out","w",stdout);
ll n,k;
n=read();k=read();
ll i,j;
sum[0]=0;
for(i=1;i<=n;i++)
{
a[i]=read();
sum[i]=sum[i-1]+a[i];
}
f[0]=0;h=t=1;q[1]=0;
for(i=1;i<=n+1;i++)
{
if(q[h]<i-k-1) h++;
f[i]=f[q[h]]+sum[i-1]-sum[q[h]];
while(h<=t&&f[q[t]]-sum[q[t]]<=f[i]-sum[i]) t--;
q[++t]=i;
}
cout<<f[n+1]<<endl;
return 0;
}