zoukankan      html  css  js  c++  java
  • hdu3507 Print Article(斜率DP优化)

    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

    5 5
    5
    9
    5
    7
    5

    Sample Output

    230
    这是一道斜率优化的模板题吧。斜率优化算是真的弄懂了个大概,不然第一次听的时候什么也不会。
    就是开头就是判断一个条件,不断取出头,保证最优,队列中的就是满足1比2优,2比3优,这样,因为后者进入的时间迟,所以又可以成为最优解,我注释了很多。
     1 #include<iostream>  
     2 #include<cstdio>   
     3 #include<algorithm>  
     4 #include<cmath>
     5 #include<cstring>
     6  
     7 typedef long long LL;  
     8 using namespace std;  
     9   
    10 const int NN=500007;
    11 
    12 int n,m;  
    13 int dp[NN],sum[NN],q[NN];  
    14   
    15 int GetY(int i,int j)
    16 {  
    17     return sum[i]*sum[i]+dp[i]-(sum[j]*sum[j]+dp[j]);  
    18 }  
    19   
    20 int GetX(int i,int j)
    21 {  
    22     return 2*(sum[i]-sum[j]);  
    23 }  
    24   
    25 int main()
    26 {
    27     int x;  
    28     while(~scanf("%d%d",&n,&m))
    29     {  
    30         int head=0,tail=0;  
    31         q[tail++]=0;//这一步必须,因为可能前i个数全部作为一段才是最小值   
    32         for(int i=1;i<=n;i++)
    33         {  
    34             scanf("%d",&x); 
    35             sum[i]=sum[i-1]+x;
    36             while(head+1<tail&&GetY(q[head+1],q[head])<=GetX(q[head+1],q[head])*sum[i])
    37                 head++;//更新最优的点
    38             dp[i]=(sum[i]-sum[q[head]])*(sum[i]-sum[q[head]])+m+dp[q[head]];//计算dp[i]的最小值
    39             while(head+1<tail&&GetY(i,q[tail-1])*GetX(q[tail-1],q[tail-2])<=GetY(q[tail-1],q[tail-2])*GetX(i,q[tail-1]))
    40                 tail--;//以k,j,i为判断斜率,然后去掉j。  
    41             q[tail++]=i;  
    42         }  
    43         printf("%d
    ",dp[n]);  
    44     }  
    45 }  
  • 相关阅读:
    Nginx性能测试
    Centos 7.0设置/etc/rc.local无效问题解决
    Centos 7.0系统服务管理
    Centos 7.0设置静态IP
    importError:cannot import name imsave/imread等模块
    一位父亲写给儿子的信:今天你努力一点,比将来低头求人强100倍
    清华大学计算机学科推荐学术会议和期刊列表---人工智能与模式识别
    在使用python语言的open函数时,提示错误OSError: [Errno 22] Invalid argument: ‘文件路径’
    论文阅读笔记---HetConv
    typeerror: __init__() missing 2 required positional arguments: 'inputs' and 'outputs'
  • 原文地址:https://www.cnblogs.com/fengzhiyuan/p/7465154.html
Copyright © 2011-2022 走看看