hdu 3507

Zero has an old printer that doesn't work well sometimes. As it is antique, he still like to use it to print articles. But it is too old to work for a long time and it will certainly wear and tear, so Zero use a cost to evaluate this degree.
One day Zero want to print an article which has N words, and each word i has a cost Ci to be printed. Also, Zero know that print k words in one line will cost

M is a const number.
Now Zero want to know the minimum cost in order to arrange the article perfectly.
 

 

Input
There are many test cases. For each test case, There are two numbers N and M in the first line (0 ≤ n ≤ 500000, 0 ≤ M ≤ 1000). Then, there are N numbers in the next 2 to N + 1 lines. Input are terminated by EOF.
 

 

Output
A single number, meaning the mininum cost to print the article.
 

 

Sample Input
  
  
5 5 5 9 5 7 5
 

 

Sample Output
230
   题目意思比较明了,我就不解释太多了。这题一开始时以为是数学题,后来发现里面其实可以出现负数,那么dp是一个不错的选择了。
但刚开始的时候没接触过斜率优化dp,所以一直tle,直到找到下面这份用单调队列+斜率优化dp的代码,很赞~
这是那位大牛的blog,上有比较好的解释。这里就附代码吧,其实和他的几乎一样(抄的就是如此)。。。。

 

#include<cstdio>
#include<iostream>
using namespace std;
const int M=500100;
__int64 a[M],sum[M];
__int64 num[M],dp[M];
int front,rear;
int n,m;
 

__int64 g(__int64 a,__int64 b)
{
 return dp[a]-dp[b]+sum[a]*sum[a]-sum[b]*sum[b];
}
__int64 s(__int64 a,__int64 b)
{
 return 2*(sum[a]-sum[b]);
}
 

__int64 top(__int64 t)         // 单调队列
{
 while(front-rear>0 && g(a[rear],a[rear+1])>=t*s(a[rear],a[rear+1])) rear++;
 return a[rear];
}
 

void push(__int64 t)     // 单调队列
{
 while(front-rear>0 && g(t,a[front])*s(a[front],a[front-1])<=s(t,a[front])*g(a[front],a[front-1])) front--;
 a[++front]=t;
}
 

int main()
{
 // freopen("in.txt","r",stdin);
 while(scanf("%d%d",&n,&m)==2)
 {
  int i,j;
  sum[0]=0;
  front=0;
  rear=1;
  for(i=1;i<=n;i++)
  {
   scanf("%I64d",&a[i]);
   sum[i]=sum[i-1]+a[i];
  }
  push(0);
  for(i=1;i<=n;i++)
  {
   j=top(sum[i]);//这里是关键,通过用单调队列直接输出1——i内的最优值的下标j,从而实
                 //在O(n)时间内完成dp,dp[i]表示的是从1到i时的最小值
   dp[i]=dp[j]+(sum[i]-sum[j])*(sum[i]-sum[j])+m;
   push(i);
  }
  printf("%I64d/n",dp[n]);
 }
 return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值