Fork me on GitHub

「HDU3507」Print Article 斜率优化dp

Links there:HDU-3507-PrintArticle

题意

将$n$个数分成若干个区间,每个区间的代价为区间和的平方加上一个常数$m$,求最小代价.

思路

考虑斜率优化,假设存在$x<y$, $x$的转移比$y$优.

则有

维护一个凸包就完事了.

(完了我更新博客越来越懒了 难道这就是颓废退役的前兆?!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//my vegetable has exploded. :(
#include<bits/stdc++.h>
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
#define MM(x,y) memset(x,y,sizeof(x))
#define MCPY(a,b) memcpy(a,b,sizeof(b))
#define pb push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,b,a) for(int i=b;i>=a;i--)
#define fi first
#define se second
using namespace std;
#define int long long

inline int quickpow(int m,int n,int p){int b=1;while(n){if(n&1)b=b*m%p;n=n>>1;m=m*m%p;}return b;}
inline int getinv(int x,int p){return quickpow(x,p-2,p);}
inline int read(void){
int x=0,f=1;char ch=getchar();
while(!isdigit(ch)){f=ch=='-'?-1:1;ch=getchar();}
while(isdigit(ch)){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return x * f;
}
const int MAXN = 5e5+100;
int sum[MAXN],a[MAXN],M,N;
int f[MAXN],q[MAXN];
double calc(int x,int y){return 1.0 * (f[y] - f[x] + (sum[y]*sum[y]) - (sum[x]*sum[x]))/(2*(sum[x]-sum[y]));}

///------------------head------------------

signed main(signed argc, char *argv[]){
scanf("%lld %lld",&N,&M); {
MM(f,0);MM(q,0);
rep(i,1,N) sum[i] = sum[i-1] + read();
int l = 0,r = 0;
rep(i,1,N)
{
while(l < r && calc(q[l],q[l+1]) < sum[i]) ++l;
int j = q[l];
f[i] = f[j] + (sum[i] - sum[j]) * (sum[i] - sum[j]) + M;
while(l < r && calc(q[r-1],q[r]) > calc(q[r],i)) --r;
q[++r] = i;
}
printf("%lld\n",f[N]);
}
return 0;
}

/* Examples: */
/*

*/

/*

*/