在学习斜率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
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.
5 5 5 9 5 7 5Sample 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;
}