【动态规划15】hdu3057 Print Article(斜率优化入门)

来源:互联网 发布:linux pipe 编辑:程序博客网 时间:2024/06/07 21:53

题目描述

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(ni=1Ci)2+M
M is a const number.
Now Zero want to know the minimum cost in order to arrange the article perfectly.

就是一个数列a[N],每次可以从中选出一个区间输出,代价为区间和的平方+M,求全部输出的最小代价。

输入输出格式

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.
A single number, meaning the mininum cost to print the article.

直接暴力想转移O(n^2)那就很显然了,设f[i]输出为前i位的最少代价。
先维护a[N]的前缀和pre,然后就很显然了。
f[i]=min(f[j]+(pre[i]pre[j])2+M)(i>j)
但是这道题的数据范围中n<=500000,O(n^2)的时间复杂度那就炸到天上去了。
k<j<i
我们先设i从j转移比从k转移的情况更优,则有
f[j]+(pre[i]pre[j])2<f[k]+(pre[i]pre[k])2(消掉M)
f[j]+pre[i]2+pre[j]22pre[i]pre[j]<f[k]+pre[i]2+pre[k]22pre[i]pre[k]
f[j]+pre[j]2f[k]pre[k]2<2pre[i](pre[j]pre[k])
pre[i]>(f[j]+pre[j]2)(f[k]+pre[k]2)2pre[j]2pre[k]

这时候我们发现这个式子当中j与k的组成元素是对应的。

xj=2*pre[j]
xk=2*pre[k]
yj=pre[j]2+f[j]
yk=pre[k]2+f[k]
原式变为pre[i]>yjykxjxk
而此时,式子右边的值可以看成两个点(xj,yj),(xk,yk)组成的直线的斜率的值。记这种斜率为K[j][k]。
且由于K[j][k]<pre[i]<pre[i+p](p>=1),故若k优于j,那么k一定恒优于j
现在我们再来考虑三个点的情况,设j<k<l
K[j][k]<pre[i]等价于决策k优于决策j
K[j][k]>K[k][[l]
{
  ①若K[k,l]<pre[i],那么显然l要优于k
  ②若K[k,l]>pre[i],则K[j][k]>K[k][l]>pre[i],那么决策j是优于k的
  综上,此时k一定不会是最优的。
}
那么只要在每次转移的时候维护一个队列,每次从队头开始转移就显然了。
(别忘了开long long)

#include<bits/stdc++.h>#define fer(i,j,n) for(int i=j;i<=n;i++)#define far(i,j,n) for(int i=j;i>=n;i--)#define ll long longconst int maxn=500010;const int INF=1e9+7;using namespace std;/*----------------------------------------------------------------------------*/inline ll read(){    char ls;ll x=0,sng=1;    for(;ls<'0'||ls>'9';ls=getchar())if(ls=='-')sng=-1;    for(;ls>='0'&&ls<='9';ls=getchar())x=x*10+ls-'0';    return x*sng;}/*----------------------------------------------------------------------------*/ll n,m;ll pre[maxn],f[maxn];ll q[maxn];ll calcK(int j,int k){    if(pre[j]==pre[k])        if(f[j]>f[k])return -1;        else return INF;    return (f[j]+pre[j]*pre[j]-f[k]-pre[k]*pre[k])/(2*pre[j]-2*pre[k]);}int main(){    while(scanf("%lld%lld",&n,&m)!=EOF)    {        fer(i,1,n)        pre[i]=read()+pre[i-1];        int h=0,t=0;        fer(i,1,n)        {            while(h<t&&calcK(q[h],q[h+1])<pre[i])h++;            f[i]=f[q[h]]+(pre[i]-pre[q[h]])*(pre[i]-pre[q[h]])+m;            while(h<t&&calcK(q[t-1],q[t])>calcK(q[t],i))t--;            q[++t]=i;        }        cout<<f[n]<<endl;    }}
原创粉丝点击