我决定改变我的博客版式。。。
标签:dp,斜率优化
这其实是一道斜率优化的模版题(虽然说我卡了很久才AC),话不多说先上题意。
原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=3507
Print Article
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
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
题意翻译成中文,大意就是把n个数分成若干块,对于每一块计算
我们可以很容易地想到用dp,直接暴力循环时间复杂度为O(n^3),这显然是不能接受的,所以我们可以利用前缀和将复杂度降到O(n^2),下面贴代码(注意这不是重点!!!)
#include<cstdio>
#include<algorithm>
#include<cstring>
#define s(x,y) (a[y]-a[x])
#define maxn 500000
using namespace std;
int f[maxn],a[maxn],c[maxn],i,j,n,m;
int main()
{
while ((scanf("%d%d",&n,&m))!=EOF)
{
memset(f,0x7f,sizeof(f)); f[0]=0; a[0]=0;
for (i=1;i<=n;i++) scanf("%d",&c[i]),a[i]=a[i-1]+c[i];
for (i=1;i<=n;i++)
for (j=0;j<i;j++)
f[i]=min(f[i],f[j]+s(j,i)*s(j,i)+m);
printf("%d\n",f[n]);
}
return 0;
}
很明显对于题目中n<=500000,还有多组数据,这肯定会TLE,所以我们需要用斜率优化将时间复杂度降到O(n)。(这才是重点)
根据上面的代码,在这我们令sum[i]表示前i项的和,在第i个循环中,如果点j优于点k,那么有
将上式化简,可以得到(具体过程请大家自己推算一遍)
再令y(k)=dp[k]+sum[k]^2,x(k)=2sum[k],可得
这就是所谓的“斜率”,如果上式成立,那么表明点j优于点k,那么以后都不用再去考虑点k了。需要一个队列去实现,具体看代码(注意计算过程中小于等于号的方向,很坑)
#include<cstdio>
#include<algorithm>
#include<cstring>
#define maxn 500050
#define y(r) (f[r]+a[r]*a[r])
#define x(r) (2*a[r])
#define up(r,t) (y(r)-y(t))
#define down(r,t) (x(r)-x(t))
#define dp(r,t) (f[t]+m+(a[t]-a[r])*(a[t]-a[r]))
using namespace std;
int f[maxn],a[maxn],c,i,n,m,q[maxn],head,tail,r,t;
int main()
{
while ((scanf("%d%d",&n,&m))!=EOF)
{
a[0]=0; memset(f,0,sizeof(f)); memset(q,0,sizeof(q));
for (i=1;i<=n;i++) scanf("%d",&c),a[i]=a[i-1]+c;
head=tail=0; q[tail++]=0;
for (i=1;i<=n;i++)
{
while (head+1<tail&&up(q[head+1],q[head])<=a[i]*down(q[head+1],q[head])) head++;
f[i]=dp(i,q[head]);
while (head+1<tail&&up(i,q[tail-1])*down(q[tail-1],q[tail-2])<=up(q[tail-1],q[tail-2])*down(i,q[tail-1])) tail--;
q[tail++]=i;
}
printf("%d\n",f[n]);
}
return 0;
}
如有意见或建议,欢迎在评论区提出。