[HNOI2008]玩具装箱TOY
链接:https://www.luogu.org/problemnew/show/P3195
题解:
dp方程很显然
然后会发现这个是可以用斜率优化的
代码:
#include <bits/stdc++.h>
using namespace std;
#define maxn 100000
#define ll long long
ll n,L,a[maxn],sum[maxn],q[maxn],h,t,dp[maxn];
ll getdp(ll i,ll j)
{
return(dp[j]+pow(sum[i]-sum[j]-L,2));
}
ll getup(ll i,ll j)
{
return(dp[i]+sum[i]*sum[i]+2*sum[i]*L-
(dp[j]+sum[j]*sum[j]+2*sum[j]*L));
}
ll getdown(ll i,ll j)
{
return(2*sum[i]-2*sum[j]);
}
int main()
{
std::ios::sync_with_stdio(false);
cin>>n>>L; L++;
for (ll i=1;i<=n;i++) cin>>a[i];
for (ll i=1;i<=n;i++) sum[i]=sum[i-1]+a[i]+1;
h=1; t=1; q[h]=0;
for (ll i=1;i<=n;i++)
{
while (h<t&&getup(q[h+1],q[h])
<=(sum[i]*getdown(q[h+1],q[h]))) h++;
dp[i]=getdp(i,q[h]);
while (h<t&&getup(i,q[t])*getdown(q[t],q[t-1])<=
getup(q[t],q[t-1])*getdown(i,q[t])) t--;
q[++t]=i;
}
cout<<dp[n];
}
代码挺简单的,改一下子函数的模板就好了