您的位置:首页 > 其它

【HDU3507】【斜率优化DP】Print Article题解

2017-05-13 11:50 232 查看
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.

Sample Input

5 5

5

9

5

7

5

Sample Output

230

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 500005;
int n,m,h,t;
int f[maxn],s[maxn],q[maxn];

inline int x(int u, int v) { return (s[u]-s[v])<<1; }

inline int y(int u, int v) { return f[u]+s[u]*s[u]-(f[v]+s[v]*s[v]); }

inline bool check1(int i) { return y(q[h+1], q[h]) <= s[i]*x(q[h+1], q[h]); }

inline bool check2(int i) { return y(i, q[t])*x(q[t], q[t-1]) <= y(q[t], q[t-1])*x(i, q[t]); }

int main() {
while(scanf("%d%d",&n,&m) != EOF) {
for(int i = 1; i <= n; i++) scanf("%d",&s[i]), s[i] += s[i-1];
q[1] = 0; h = t = 1;
for(int i = 1; i <= n; i++) {
while(h < t && check1(i)) h++;
f[i] = f[q[h]]+m+(s[i]-s[q[h]])*(s[i]-s[q[h]]);
while(h < t && check2(i)) t--;
q[++t] = i;
}
printf("%d\n",f
);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: