题目链接:戳这里
|
Print ArticleTime Limit: 9000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submission(s): 14818 Accepted Submission(s): 4626
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
Sample Output
|
题解:很容易想到dp方程:dp[i]表示输出前i的数的最小代价。
转移:dp[i]=min{dp[j]+(sum[i]-sum[j])^2+M),其中sum[i]表示前缀和,1<=j<=i。
因为转移是n^2复杂度,而n是500000,直接转移无法接受,考虑斜率优化。
设k<j且j比k优,可推得dp[j]+(sum[i]-sum[j])^2+M <= dp[k]+(sum[i]-sum[k])^2+M。
移项化简即可。
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int read()
{
char c;int sum=0,f=1;c=getchar();
while(c<'0' || c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0' && c<='9'){sum=sum*10+c-'0';c=getchar();}
return sum*f;
}
int n,m;
LL sum[500005],dp[500005];
int q[500005],head,tail;
LL sqr(LL x){return x*x;}
LL slop(int j,int k)
{
return dp[j]+sqr(sum[j])-dp[k]-sqr(sum[k]);
}
LL slop2(int j,int k)
{
return 2*sum[j]-2*sum[k];
}
int main()
{
while(scanf("%d%d",&n,&m)==2)
{
sum[0]=dp[0]=0;
for(int x,i=1;i<=n;i++)
{
x=read();
sum[i]=sum[i-1]+x;
}
head=tail=0;q[tail++]=0;
for(int i=1;i<=n;i++)
{
while(head+1<tail && slop(q[head+1],q[head])<=sum[i]*slop2(q[head+1],q[head]))
head++;
int now=q[head];
dp[i]=dp[now]+sqr(sum[i]-sum[now])+m;
while(head+1<tail && slop(i,q[tail-1])*slop2(q[tail-1],q[tail-2])<=slop(q[tail-1],q[tail-2])*slop2(i,q[tail-1]))
tail--;
q[tail++]=i;
}
printf("%lld\n",dp[n]);
}
return 0;
}