1. 程式人生 > >Print Article HDU 3507(斜率DP入門模板題)

Print Article HDU 3507(斜率DP入門模板題)

Print Article

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


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

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

分析:首先純暴力是肯定不行的。因為其狀態轉移方程為:dp[i]=dp[j]+M+(sum[i]-sum[j])^2;其中dp[i]表示輸出到i的時候最少的花費,sum[i]表示從a[1]到a[i]的數字和。所以會想到斜率優化。

詳見  http://www.cnblogs.com/ka200812/archive/2012/08/03/2621345.html

程式碼如下:

/* Author:kzl */
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxx = 500000+500;
int n,m;
int dp[maxx],sum[maxx],q[maxx];
int aa;

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

int getdown(int i,int j){
return 2*(sum[i] - sum[j]);
}

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

int main(){
    sum[0] = 0;
while(scanf("%d%d",&n,&m)!=EOF)
{
    for(int i=1;i<=n;i++){
    scanf("%d",&aa);
    sum[i] = sum[i-1] + aa;
    }

    dp[0] = 0;
    int head = 0;
    int tail = 0;
    q[tail++] = 0;
    for(int i=1;i<=n;i++){
        while(head+1<tail && getup(q[head+1],q[head])<sum[i]*getdown(q[head+1],q[head])){
            head++;
        }
        dp[i] = getdp(i,q[head]);
         while(head+1<tail && getup(i,q[tail-1])*getdown(q[tail-1],q[tail-2]) <= getup(q[tail-1],q[tail-2])*getdown(i,q[tail-1])){
            tail--;
         }
         q[tail++] = i;
    }
    printf("%d\n",dp[n]);
}
return 0;
}