题目链接:戳我
很明显的转移方程——
设(dp[i])表示放到玩具i所需要的最小代价,那么(dp[i]=min(dp[i],dp[j]+(i-j+sum[i]-sum[j]-l)^2))
来个暴力开O2我又骗到了70分。。。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define MAXN 50010
using namespace std;
int n,l;
int a[MAXN];
long long sum[MAXN],dp[MAXN];
int main()
{
#ifndef ONLINE_JUDGE
freopen("ce.in","r",stdin);
#endif
scanf("%d%d",&n,&l);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum[i]+=sum[i-1]+a[i];
}
for(int i=1;i<=n;i++) dp[i]=(long long)1e18;
for(int i=1;i<=n;i++)
for(int j=0;j<i;j++)
dp[i]=min(dp[i],dp[j]+1ll*(i-j-1+sum[i]-sum[j]-l)*(i-j-1+sum[i]-sum[j]-l));
printf("%lld
",dp[n]);
return 0;
}
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#define MAXN 100010
using namespace std;
int n,l,head=1,tail=1;
long long sum[MAXN],k[MAXN],q[MAXN],dp[MAXN];
inline long long a(int p){return sum[p]+p;}
inline long long b(int p){return sum[p]+p+l+1;}
inline long long x(int p){return b(p);}
inline long long y(int p){return dp[p]+b(p)*b(p);}
inline double calc(int p,int q){return (y(p)-y(q))/(x(p)-x(q));}
int main()
{
#ifndef ONLINE_JUDGE
freopen("ce.in","r",stdin);
#endif
scanf("%d%d",&n,&l);
for(int i=1;i<=n;i++)
{
scanf("%lld",&k[i]);
sum[i]=sum[i-1]+k[i];
}
for(int i=1;i<=n;i++)
{
while(head<tail&&calc(q[head],q[head+1])<2*a(i)) head++;
dp[i]=1ll*y(q[head])-1ll*2*a(i)*x(q[head])+a(i)*a(i);
while(head<tail&&calc(q[tail-1],q[tail])>calc(q[tail-1],i)) tail--;
q[++tail]=i;
}
printf("%lld
",(long long)dp[n]);
return 0;
}