HDU3507 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.

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.

一眼就看出来要用动态规划。
dp[i]表示到i为止的最小费用,朴素的状态转移方程为dp[i]=max{dp[j]+(s[i]-s[j])^2+m},其中s为前缀和数组。
因为有s[i]*s[j]的交叉项,考虑斜率优化。
设目前正在考虑i,对于j>k,j比k优的条件是
dp[j]+(s[i]-s[j])^2+m< dp[k]+(s[i]-s[k])^2+m
记f(i)=dp[i]+s[i]^2,g(i)=2*s[i]
化简得s[i]>(f(j)-f(k))/(g(j)-g(k))
维护一个斜率递增的下凸壳即可。
对于每个i,操作顺序如下:
1.如果次队首比队首优,队首出队。
2.取队首为解。
3.如果插入后不满足下凸壳性质,队尾出队。
4.插入到队尾。

#include<cstdio>
#include<cstring>
#define L long long
L dp[500010],s[500010];
int q[500010];
L f(int x)
{
    return dp[x]+s[x]*s[x];
}
L g(int x)
{
    return 2*s[x];
}
int main()
{
    int i,j,k,m,n,p,hd,tl;
    L x,y,z;
    while (scanf("%d%d",&n,&m)==2)
    {
        q[1]=0;
        for (i=1;i<=n;i++)
        {
            scanf("%d",&p);
            s[i]=s[i-1]+p;
        }
        hd=0;
        tl=1;
        for (i=1;i<=n;i++)
        {
            while (tl>hd&&
              (g(q[hd+1])-g(q[hd]))*s[i]>
              f(q[hd+1])-f(q[hd]))
                hd++;
            dp[i]=dp[q[hd]]+(s[i]-s[q[hd]])*(s[i]-s[q[hd]])+m;
            while (tl>hd&&
              (f(q[tl])-f(q[tl-1]))*(g(i)-g(q[tl]))>=
              (g(q[tl])-g(q[tl-1]))*(f(i)-f(q[tl])))
                tl--;
            q[++tl]=i;
        }
        printf("%lld\n",dp[n]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值