E53 斜率优化DP [HNOI2008]玩具装箱
视频链接:463 斜率优化DP [HNOI2008]玩具装箱_哔哩哔哩_bilibili
#include <iostream> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int N = 50010; int n,L,q[N]; LL s[N],f[N]; double slope(int i,int j){ return 1.0*(f[i]+(s[i]+i)*(s[i]+i)-f[j]-(s[j]+j)*(s[j]+j)) /(s[i]+i==s[j]+j?1e-9:s[i]+i-s[j]-j); } int main(){ scanf("%d%d",&n,&L); L++; 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]+i-L)) h++; int j=q[h]; f[i]=f[j]+(s[i]+i-s[j]-j-L)*(s[i]+i-s[j]-j-L); } printf("%lld\n",f[n]); }
#include <iostream> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int N = 50010; int n,L,q[N]; LL s[N],f[N]; LL dy(int i,int j){return f[i]+(s[i]+i)*(s[i]+i)-f[j]-(s[j]+j)*(s[j]+j);} LL dx(int i,int j){return s[i]+i-s[j]-j;} int main(){ scanf("%d%d",&n,&L); L++; 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 && dy(i-1,q[t])*dx(q[t],q[t-1])<=dx(i-1,q[t])*dy(q[t],q[t-1])) t--; q[++t]=i-1; while(h<t && dy(q[h+1],q[h])<=dx(q[h+1],q[h])*2*(s[i]+i-L)) h++; int j=q[h]; f[i]=f[j]+(s[i]+i-s[j]-j-L)*(s[i]+i-s[j]-j-L); } printf("%lld\n",f[n]); }