Print Article

Print Article
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 20528 Accepted Submission(s): 6240

Problem Description

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[i]表示到达i时取到的最大值
d p [ i ] = m i n ( d p [ j ] + ( ( s u m [ i ] s u m [ j ] ) 2 + m ) ) ( 0 &lt; = j &lt; = i 1 ) dp[i]=min(dp[j]+({(sum[i]-sum[j])}^2+m) )(0&lt;=j&lt;=i-1) dp[i]=min(dp[j]+((sum[i]sum[j])2+m))(0<=j<=i1)
则O(n^2)(n=1e5)过大(1s约为2e7-2e8)

斜率优化
不妨设
k<j<i
d p [ k ] + ( s u m [ i ] s u m [ k ] ) 2 + m &lt; = d p [ j ] + ( ( s u m [ i ] s u m [ j ] ) 2 + m ) dp[k]+{(sum[i]-sum[k])}^2+m&lt;=dp[j]+((sum[i]-sum[j])^2+m) dp[k]+(sum[i]sum[k])2+m<=dp[j]+((sum[i]sum[j])2+m)

( d p [ j ] + s u m [ j ] 2 ) ( d p [ k ] + s u m [ k ] 2 ) s u m [ j ] s u m [ k ] s u m [ i ] \frac{(dp[j]+sum[j]^2)−(dp[k]+sum[k]^2)}{sum[j]−sum[k]} ≤sum[i] sum[j]sum[k](dp[j]+sum[j]2)(dp[k]+sum[k]2)sum[i]
若满足,则j比k优


#include<bits/stdc++.h>
#define N 500005
#define ll long long
using namespace std;


int n,m;
int A[N];
int Q[N],dp[N];
int x[N],y[N];
int getup(int k,int j)
{
	return y[j]-y[k];
}

int getdown(int k,int j)
{
	return x[j]-x[k];
}

int calc(int j,int i)
{
	return dp[j]+(A[i]-A[j])*(A[i]-A[j])+m;
}


int main(){
	while (scanf("%d",&n)!=EOF)
	  {
	  	scanf("%d",&m);
	  	for (int i=1;i<=n;i++)
	  	{
	  		scanf("%d",&A[i]);
	  		A[i]+=A[i-1];//printf("a[%d]=\n%d\n",i,A[i]);
		}
		int l=0,r=0;
		Q[r++]=0;
		dp[0]=0;
		//printf("r=%d,Q[r]=%d\n",r-1,Q[r]);
		for (int i=1;i<=n;i++)
		{
			while (l+1<r&&getup(Q[l],Q[l+1])<=getdown(Q[l],Q[l+1])*A[i]) l++;
			dp[i]=calc(Q[l],i);
			x[i]=2*A[i];
			y[i]=dp[i]+A[i]*A[i];
			while (l+1<r&&getup(Q[r-1],i)*getdown(Q[r-2],Q[r-1])<=getup(Q[r-2],Q[r-1])*getdown(Q[r-1],i)) r--;
			Q[r++]=i;
		}
	  
	  printf("%d\n",dp[n]);
     }
	
	return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务