hdu 3507 Print Article


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.

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.

ouput

A single number, meaning the mininum cost to print the article.

 5 5 5 9 5 7 5

230

 第一道斜率题目,总之做dp很苦逼。事情是这个样子的------首先列出dp方程

很显然的一个方程 dp[i]=min(dp[i],dp[j]+(sum[i]-sum[j])^2) . 复杂度O(n^2) 

直接用的话TLE.

要用到斜率优化。 考虑 k<j<i ,时如果 在j点比k点更优则有

dp[j]+[sum(i)-sum(j)]^2 <dp[k]+[sum(i)-sum(k)]^2

整理可得 (dp[j]-sum[j]^2)-(dp[k]-sum[k]^2) <sum[i]*2*(sum[j]-sum[k]);

得到一个类似   y1-y2<k*(x1-x2); 的式子。然后考虑到这个式子的成立很容易得知

整个优先队列所要保存的点必须呈现斜率上升的趋势,否则直接将此点抛弃。

 边维护单调队列边求出dp值时间复杂度是O 

  1 #include<cstdio>

 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 const int MAX = 500000+10;
 6 int n,m;
 7 int dp[MAX],num[MAX];
 8 int deq[MAX],sum[MAX];
 9 int gety(int j,int k)
10 {
11     return dp[j]+sum[j]*sum[j]-(dp[k]+sum[k]*sum[k]);
12 }
13 int getx(int j,int k)
14 {
15     return 2*(sum[j]-sum[k]);
16 }
17 int getdp(int i,int j)
18 {
19     return dp[j]+(sum[j]-sum[i])*(sum[j]-sum[i])+m;
20 }
21 int main()
22 {
23 
24     while(scanf("%d %d",&n,&m)==2)
25     {
26         sum[0]=0;
27         for(int i=1;i<=n;i++)
28         {
29             scanf("%d",&num[i]);
30             sum[i]=sum[i-1]+num[i];
31         }
32         memset(dp,0,sizeof(dp));
33         int front=0,rear=0;
34         for(int i=1;i<=n;i++)
35         {
36             while(front+1<rear&&gety(deq[front+1],deq[front])<=sum[i]*getx(deq[front+1],deq[front]))
37             front++;
38             dp[i]=getdp(i,deq[front]);
39             while(front+1<rear&&gety(i,deq[rear-1])*getx(deq[rear-1],deq[rear-2])<gety(deq[rear-1],deq[rear-2])*getx(i,deq[rear-1]))
40             rear--;
41 
42             deq[rear++]=i;
43 
44         }
45         printf("%d ",dp[n]);
46     }
47     return 0;
48 }


原文地址:https://www.cnblogs.com/acvc/p/3631528.html