[HDU 3507]Print Article(斜率优化Dp)

本文介绍了一种使用斜率优化DP解决打印文章成本最小化问题的方法。主人公零号有一台老式打印机,需要通过特定算法来计算出最优的打印方案,以减少因打印机老化带来的额外成本。文章详细展示了算法实现过程及代码细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Solution

斜率优化Dp入门题

代码明明很简单然而一开始写挂了(??)我还对拍了啊喂…什么错都没拍出来

每次交都觉得能A,每次都证实是错觉,结果成为了HDU交的次数最多的一道题,想哭TvT

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
int n,m;
int sum[500005],f[500005];
int q[1000005],head,tail;
int read()
{
    int x=0,f=1;char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-')f=-1;c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=x*10+c-'0';c=getchar();
    }
    return x*f;
}
int getx(int i,int j)
{
    return f[j]+sum[j]*sum[j]-f[i]-sum[i]*sum[i];
}
int gety(int i,int j)
{
    return 2*(sum[j]-sum[i]);
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=1;i<=n;i++)
        {
            sum[i]=read();
            sum[i]+=sum[i-1];
        }
        head=tail=0;q[tail++]=0;
        for(int i=1;i<=n;i++)
        {
            while(head+1<tail&&getx(q[head],q[head+1])<=sum[i]*gety(q[head],q[head+1]))//要取到等号
            head++;
            f[i]=f[q[head]]+(sum[i]-sum[q[head]])*(sum[i]-sum[q[head]])+m;
            while(head+1<tail&&getx(q[tail-1],i)*gety(q[tail-2],q[tail-1])<=getx(q[tail-2],q[tail-1])*gety(q[tail-1],i))//顺序不能反否则符号会变
            tail--;
            q[tail++]=i;
        }
        printf("%d\n",f[n]);
    }
    return 0;
} 

 

转载于:https://www.cnblogs.com/Zars19/p/6642804.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值