整理日期按学习顺序编排,不代表原始发表时间。实际整理于 2026-10-23。
难度为阅读建议,可从 ACM 学习索引 按阶段阅读。
dp优化

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <iostream> #include <cstring> #include <algorithm> using namespace std;
typedef long long LL; const int N=1e5+10; int n,k,q[N]; LL w[N],f[N],sum;
int main(){ cin>>n>>k; k++; for(int i=1;i<=n;i++) cin>>w[i],sum+=w[i]; int h=1,t=0; LL s=1e18; for(int i=1;i<=n;i++){ while(h<=t && f[q[t]]>=f[i-1]) t--; q[++t]=i-1; if(q[h]<i-k) h++; f[i]=f[q[h]]+w[i]; if(i>n-k) s=min(s,f[i]); } cout<<sum-s; }
|


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #include <iostream> #include <cstring> #include <algorithm> using namespace std;
typedef long long LL; const int N = 500010; int n,m,q[N]; LL s[N],f[N];
double slope(int i,int j){ return (double)(f[i]+s[i]*s[i]-f[j]-s[j]*s[j]) /(s[i]==s[j]?1e-9:s[i]-s[j]); } int main(){ while(~scanf("%d%d",&n,&m)){ for(int i=1;i<=n;i++) scanf("%lld",&s[i]),s[i]+=s[i-1]; int h=1,t=0; for(int i=1;i<=n;i++){ while(h<t && slope(i-1,q[t])<=slope(q[t],q[t-1])) t--; q[++t]=i-1; while(h<t && slope(q[h+1],q[h])<=2*s[i]) h++; int j=q[h]; f[i]=f[j]+(s[i]-s[j])*(s[i]-s[j])+m; } printf("%lld\n",f[n]); } }
|