HDU-3507Print Article 斜率优化DP
生活随笔
收集整理的這篇文章主要介紹了
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_queuetypedef 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?
轉載于:https://www.cnblogs.com/ckxkexing/p/9348486.html
總結
以上是生活随笔為你收集整理的HDU-3507Print Article 斜率优化DP的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: es6 - foreach
- 下一篇: MonogoDb学习笔记