procedure2012
It's not worth it to know you're not worth it!

[关键字]:动态规划 斜率优化

[题目大意]:有n个玩具,每个玩具有一定长度,每两个玩具之间必须有一格单位的空格,且玩具序号必须连续。每造一个箱子的花费为(l-L)2l是箱子使用长度,L为常量。求出装下所有玩具的最小花费。

//============================================================================================

[分析]:明显的斜率优化动态规划。首先写出转移方程:f[i]=min{f[j]+(s[i]-s[j]+i-(j+1)-L)2},设s'[i]=s[i]+i,L'=L+1,Vx=f[x]+(s'[i]-s'[j]-L')。然后设x<y and Vx<Vy.化简不等式最后结果为:((f[x]+s'[x]*s'[x])-(f[y]+s'[y]*s'[y]))/(s'[x]-s'[y])>2*(s'[i]-L')。满足斜率优化条件,利用单调队列,

G(x,y)=((f[x]+s'[x]*s'[x])-(f[y]+s'[y]*s'[y]))/(s'[x]-s'[y]),如果G(H,H+1)<=2*(s'[i]-L')就出队头。最后的队头就是当前最有决策。入队时也要保证G函数的单调性,推掉G(t-1,t)>G(t,i)的t。

[代码]:

View Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;

const int MAXN=60000;

int n,L,h,t;
int q[MAXN];
long long f[MAXN],s[MAXN];

double Calc(int x,int y)
{
return ((f[x]+s[x]*s[x])-(f[y]+s[y]*s[y]))/(s[x]-s[y]);
}

int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
scanf("%d%d",&n,&L);
int x;
for (int i=1;i<=n;++i)
scanf("%d",&x),s[i]=s[i-1]+x+1;
//for (int i=1;i<=n;++i) printf("%d\n",s[i]);
h=t=1;
q[1]=0;
for (int i=1;i<=n;++i)
{
while (h<t && Calc(q[h],q[h+1])<=2*(s[i]-L-1)) ++h;
f[i]=f[q[h]]+(s[i]-s[q[h]]-1-L)*(s[i]-s[q[h]]-1-L);
//printf("%d %d %d\n",h,t,q[h]);
while (h<t && Calc(q[t-1],q[t])>=Calc(q[t],i)) --t;
q[++t]=i;
}
printf("%lld\n",f[n]);
return 0;
}



posted on 2012-04-07 00:25  procedure2012  阅读(346)  评论(0编辑  收藏  举报