zoukankan      html  css  js  c++  java
  • BZOJ 1010: [HNOI2008]玩具装箱toy 斜率优化dp

    Description

    P教授要去看奥运,但是他舍不下他的玩具,于是他决定把所有的玩具运到北京。他使用自己的压缩器进行压缩,其可以将任意物品变成一堆,再放到一种特殊的一维容器中。P教授有编号为1...N的N件玩具,第i件玩具经过压缩后变成一维长度为Ci.为了方便整理,P教授要求在一个一维容器中的玩具编号是连续的。同时如果一个一维容器中有多个玩具,那么两件玩具之间要加入一个单位长度的填充物,形式地说如果将第i件玩具到第j个玩具放到一个容器中,那么容器的长度将为 x=j-i+Sigma(Ck) i<=K<=j 制作容器的费用与容器的长度有关,根据教授研究,如果容器长度为x,其制作费用为(X-L)^2.其中L是一个常量。P教授不关心容器的数目,他可以制作出任意长度的容器,甚至超过L。但他希望费用最小.

    Input

    第一行输入两个整数N,L.接下来N行输入Ci.1<=N<=50000,1<=L,Ci<=10^7

    Output

    输出最小费用

    Sample Input

    5 4
    3
    4
    2
    1
    4

    Sample Output

    1

     

    题解:

    这是典型的斜率优化dp,状态也很好得到,dp[i]=min{dp[j]+(sum[i]-sum[j]+i-j-1-L)^2。斜率优化的过程可以看看我以前写的一篇博客:http://www.cnblogs.com/HarryGuo2012/p/4841215.html

    代码:

    #include<iostream>
    #include<cstring>
    #include<vector>
    #include<cstdio>
    #define MAX_N 50004
    using namespace std;
    
    typedef long long ll;
    
    ll N,L,C[MAX_N];
    ll sum[MAX_N];
    
    ll dp[MAX_N];
    
    double F(int t) {
        return sum[t] + t + 1 + L;
    }
    
    double G(int t) {
        return sum[t] + t;
    }
    
    double Y(int t){
        return dp[t]+F(t)*F(t);
    }
    
    double X(int t){
        return F(t);
    }
    
    double Slope(int u,int v) {
        return (Y(u) - Y(v)) / (X(u) - X(v));
    }
    
    int que[MAX_N];
    
    int main() {
        cin.sync_with_stdio(false);
        cin>>N>>L;
        for (int i = 1; i <= N; i++) {
            cin>>C[i];
            sum[i] = sum[i - 1] + C[i];
        }
        int front = 0, rear = 0;
        que[rear++] = 0;
        //dp[1] = (C[1] - L) * (C[1] - L);
        for (int i = 1; i <= N; i++) {
            while (rear - front > 1 && Slope(que[front], que[front + 1]) <= 2 * G(i))front++;
            int j = que[front];
            ll tmp = sum[i] - sum[j] + i - j - 1 - L;
            dp[i] = dp[j] + tmp * tmp;
            while (rear - front > 1 && Slope(que[rear - 1], que[rear - 2]) >= Slope(que[rear - 1], i))rear--;
            que[rear++] = i;
        }
        cout<<dp[N]<<endl;
        return 0;
    }
  • 相关阅读:
    牛客网编程练习之网易2017校招题:下厨房
    牛客网编程练习之网易2017校招题:数字翻转
    牛客网编程练习之京东2017校招题:幸运数
    牛客网编程练习之去哪儿网2017校招题:身份证分组
    牛客网编程练习之网易2017校招题:解救小易
    牛客网编程练习之腾讯2017校招题:游戏任务标记
    Fiddler实现对手机抓包
    sshpass笔记
    图片反色
    LintCode题解之统计数字
  • 原文地址:https://www.cnblogs.com/HarryGuo2012/p/4844017.html
Copyright © 2011-2022 走看看