斜率DP模板

在学习斜率dp之前,看过很多大牛的博客,推荐一篇帮助理解,斜率dp就是通过得到斜率判断趋势,把O(n*n)的问题变成O(n)的问题,减少时间复杂度。具体过程比较固定。

1.找到关系表达式

2.推出斜率式

然后直接套模板就行了。当然有些问题比较复杂,大家灵活使用总结就行了。

HDU 3507  

Print Article

 

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. 
InputThere 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.OutputA single number, meaning the mininum cost to print the article.Sample Input
5 5
5
9
5
7
5
Sample Output
230

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdio>

using namespace std;

int dp[500100], sum[500100];
int q[500100];
int n, m;

int getDp(int i, int j){
    return dp[j] + m + (sum[i] - sum[j]) * (sum[i] - sum[j]);
}

int getUp(int k, int j){
    return dp[j] + sum[j] * sum[j] - (dp[k] + sum[k] * sum[k]);
}

int getDown(int k,int j){
    return 2 * (sum[j] - sum[k]);
}

int main(){
    int temp, l, r;
    while(scanf("%d%d", &n, &m) != EOF){
        sum[0] = 0;
        for(int i = 1; i <= n; i++){
            scanf("%d", &temp);
            sum[i] = sum[i - 1] + temp;
        }
        l = r = 1;
        q[r] = 0;
        for(int i = 1; i <= n; i++){
            while(l < r && getUp(q[l], q[l + 1]) <= sum[i] * getDown(q[l], q[l + 1]))
                l++;
            dp[i] = getDp(i, q[l]);
            while(l < r && getUp(q[r], i) * getDown(q[r - 1], q[r]) <= getUp(q[r - 1], q[r]) * getDown(q[r], i))
                r--;
            q[++r] = i;
        }
        printf("%d\n",dp[n]);
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值