HDU 3507 Print Article
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板子题.单调队列维护 x满足递增 非常好写
一个结论:满足条件的点一定在一个凸包的底端,所以我们维护凸包底端的点即可
1 #include <algorithm> 2 #include <iostream> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cstdio> 6 #include <cmath> 7 using namespace std; 8 typedef long long ll; 9 const int N=500005; 10 int gi(){ 11 int str=0;char ch=getchar(); 12 while(ch>'9' || ch<'0')ch=getchar(); 13 while(ch>='0' && ch<='9')str=(str<<1)+(str<<3)+ch-48,ch=getchar(); 14 return str; 15 } 16 int n,m,a[N],q[N];ll sum[N],f[N]; 17 ll fy(int i,int j){ 18 return sum[i]*sum[i]+f[i]-sum[j]*sum[j]-f[j]; 19 } 20 ll fx(int i,int j){ 21 return ((sum[i]-sum[j])<<1); 22 } 23 void work(){ 24 int l=1,r=1,j,k; 25 q[1]=0; 26 for(int i=1;i<=n;i++)a[i]=gi(),sum[i]=sum[i-1]+a[i]; 27 for(int i=1;i<=n;i++){ 28 while(l<=r-1){ 29 j=q[l];k=q[l+1]; 30 if(fy(j,k)>=sum[i]*fx(j,k))l++; 31 else break; 32 } 33 f[i]=f[q[l]]+m+(sum[i]-sum[q[l]])*(sum[i]-sum[q[l]]); 34 while(l<=r-1){ 35 j=q[r];k=q[r-1]; 36 if(fy(i,j)*fx(j,k)<=fy(j,k)*fx(i,j))r--; 37 else break; 38 } 39 q[++r]=i; 40 } 41 printf("%lld\n",f[n]); 42 } 43 int main() 44 { 45 while(~scanf("%d%d",&n,&m)) 46 work(); 47 return 0; 48 }