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.
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;
}