hdu3507 Print Article
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 7513 Accepted Submission(s): 2341
Total Submission(s): 7513 Accepted Submission(s): 2341
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.
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]= min{ dp[j]+(sum[i]-sum[j])^2 +M } 0<j<i
<pre name="code" class="cpp">#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
#define ll long long
#define inf 0x7fffffff
#define maxn 500060
int a[maxn],dp[maxn],q[1111111],sum[maxn];
int getup(int j){
return dp[j]+sum[j]*sum[j];
}
int getdown(int j){
return 2*sum[j];
}
int main()
{
int n,m,i,j;
int front,rear;
while(scanf("%d%d",&n,&m)!=EOF)
{
a[0]=sum[0]=0;
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
front=1;rear=1;
q[rear]=0; //这里0要加到队列中,因为可能之后的i和0这两点的斜率最低(即最优),它表示的意义是把前i个都放在一起所要花的费用
for(i=1;i<=n;i++){
while(front<rear && getup(q[front+1])-getup(q[front] )<=sum[i]*(getdown(q[front+1])-getdown(q[front]))){ //这里不能写成front<=rear,因为队列里一定要有两个点才能删除一个点
front++;
}
dp[i]=dp[q[front] ]+(sum[i]-sum[q[front] ])*(sum[i]-sum[q[front] ] )+m;
while(front<rear && (getup(q[rear])-getup(q[rear-1]))*(getdown(i)-getdown(q[rear]))>=(getup(i)-getup(q[rear]))*(getdown(q[rear])-getdown(q[rear-1])) ){
rear--;
}
rear++;
q[rear]=i;
}
printf("%d\n",dp[n]);
}
return 0;
}