HDU-3507Print Article 斜率优化DP

学习:https://blog.csdn.net/bill_yang_2016/article/details/54667902

 

HDU-3507

题意:有若干个单词,每个单词有一个费用,连续的单词组合成一块有花费:(∑Ci)^2+M,问如何分单词,使得这些花费和最小。

思路:dp,但是由于数据n = 5e5,所以需要利用斜率优化dp,维护一个下凸包。

大佬的分析:http://www.cnblogs.com/ka200812/archive/2012/08/03/2621345.html;

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <list>
#include <cstdlib>
#include <iterator>
#include <cmath>
#include <iomanip>
#include <bitset>
#include <cctype>
#include <deque>
using namespace std;

#define lson (l , mid , rt << 1)
#define rson (mid + 1 , r , rt << 1 | 1)
#define debug(x) cerr << #x << " = " << x << "\n";
#define pb push_back
#define pq priority_queue

typedef long long ll;
typedef unsigned long long ull;

typedef pair<ll ,ll > pll;
typedef pair<int ,int > pii;

#define fi first
#define se second

#define OKC ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define FT(A,B,C) for(int A=B;A <= C;++A)  //用来压行
#define REP(i , j , k)  for(int i = j ; i <  k ; ++i)


const ll mos = 0x7FFFFFFF;  //2147483647
const ll nmos = 0x80000000;  //-2147483648

template<typename T>
inline T read(T&x){
    x=0;int f=0;char ch=getchar();
    while (ch<'0'||ch>'9') f|=(ch=='-'),ch=getchar();
    while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x=f?-x:x;
}
// #define _DEBUG;         //*//
#ifdef _DEBUG
freopen("input", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
/*-----------------show time----------------*/
            const int maxn =500009;
            ll dp[maxn],a[maxn];
            ll sum[maxn];
            int q[maxn];
        double slope(ll j, ll k ){  //计算斜率。
                if(sum[k]==sum[j])return 0.0;
                return(dp[j] + 1ll*sum[j] * sum[j] - (dp[k] + 1ll*sum[k]*sum[k]) )*1.0/(2 * (sum[j] - sum[k]));
        }
int main(){
            int n,m;
            while(~scanf("%d%d", &n, &m)){
                sum[0] = 0;
                for(int i=1; i<=n; i++){
                    scanf("%lld", &a[i]);
                    sum[i] = sum[i-1] + a[i];
                }
                int le = 1,ri = 1;
                q[1] = 0;  
                dp[0] = 0;
                for(int i=1; i<=n; i++){
                    while(le < ri && slope(q[le] , q[le+1]) < sum[i]) le++; //维护不等式成立的条件
                    dp[i] = dp[q[le]] + 1ll*(sum[i] - sum[q[le]]) *  (sum[i] - sum[q[le]]) + m;
                    while(le < ri && slope(q[ri] , q[ri-1]) >= slope(q[ri],i))ri--;//斜率优化,删点。
                    q[++ri] = i;
                }
                printf("%lld\n", dp[n]);
            }

    return 0;
}
HDU-3507

 

posted @ 2018-07-21 23:12  ckxkexing  阅读(155)  评论(0编辑  收藏  举报