欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HDU3507 Print Article(斜率优化DP)

程序员文章站 2022-12-04 23:51:23
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submission(s): 16213 Accepted Submission(s): 4992 Problem Descr ......

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 16213    Accepted Submission(s): 4992


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
HDU3507 Print Article(斜率优化DP)

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
 

 

Author
Xnozero
 

 

Source
 

 

Recommend
zhengfeng   |   We have carefully selected several similar problems for you:       
 
 
比较裸的斜率优化。
以前用的是斜截式推,现在改用求决策单调性的方式推了,
后者虽然计算量大,但是无脑一些
推出来之后维护一个上凸壳
推荐一篇写的非常好的博客
https://www.cnblogs.com/orzzz/p/7885971.html
不知道为啥不能写成除法的形式。。
 
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 1e6 + 10, INF = 1e9 + 10;
int N, M, a[MAXN], s[MAXN], f[MAXN], q[MAXN];
int X(int x) {
    return s[x];
}
int Y(int x) {
    return f[x] + s[x] * s[x];
}
int check(int x, int y, int i) {
    return (Y(y) - Y(x)) <= (X(y) - X(x)) * 2 * s[i];
}
int check2(int xx1, int yy1, int xx2, int yy2) {
    return ((Y(yy1) - Y(xx1)) * (X(yy2) - X(xx2))) >= ((Y(yy2) - Y(xx2)) * (X(yy1) - X(xx1)));
}
/*int slope(int x, int y) {
    return (Y(y) - Y(x)) / (X(y) - X(x));
}*/
int main() {
    //freopen("a.in", "r", stdin);
    while(scanf("%d %d", &N, &M) != EOF) {
        memset(f, 0, sizeof(f)); 
        for(int i = 1; i <= N; i++) scanf("%d", &a[i]), s[i] = s[i - 1] + a[i];
        int h = 0, t = 0;
        for(int i = 1; i <= N; i++) {
        //    if(h < t)    printf("%lf %lf\n", slope(q[h], q[h + 1]), (double)2 * s[i]);
            while(h < t && check(q[h], q[h + 1], i)) h++;
            f[i] = (f[q[h]] + (s[i] - s[q[h]]) * (s[i] - s[q[h]]) + M);
            while(h < t && check2(q[t - 1], q[t], q[t], i)) t--;
            q[++t] = i;
        }
        printf("%d\n", f[N]);
    }
    return 0;
}