# BZOJ 3437 小P的牧场 (斜率优化DP)

$f[i]=max(f[j]-(\sum_{k=j+1}^{i-1}(i-k)*b[k]))+a[i];(j

$y=f[j]-s2[j]-(j+1)*s1[j];$

$k=i,x=s1[j]$

$b=f[i]-s2[i-1]-a[i]$

 1 #include <cstdio>
2 #include <cstring>
3 #include <algorithm>
4 #define ll long long
5 #define dd double
6 #define il inline
7 #define N 1001000
8 using namespace std;
9
10 int n;
11 ll a[N],b[N],s1[N],s2[N],f[N];
12 int que[N];
13 int gc()
14 {
15     int rett=0,fh=1;char c=getchar();
16     while(c<'0'||c>'9'){if(c=='-')fh=-1;c=getchar();}
17     while(c>='0'&&c<='9'){rett=(rett<<3)+(rett<<1)+c-'0';c=getchar();}
18     return rett*fh;
19 }
20 il ll yy(int i){return f[i]-s2[i]+((ll)i+1)*s1[i];}
21 il ll xx(int i){return s1[i];}
22
23 int main()
24 {
25     scanf("%d",&n);
26     for(int i=1;i<=n;i++) a[i]=gc();
27     for(int i=1;i<=n;i++) b[i]=gc();
28     for(int i=1;i<=n;i++) s1[i]=s1[i-1]+b[i];
29     for(int i=1;i<=n;i++) s2[i]=s2[i-1]+s1[i];
30     int hd=1,tl=1;
31     for(ll i=1;i<=n;i++)
32     {
33         while(hd+1<=tl&&yy(que[hd])-i*xx(que[hd])>=yy(que[hd+1])-i*xx(que[hd+1]))
34             hd++;
35         f[i]=yy(que[hd])-i*xx(que[hd])+a[i]+s2[i-1];
36         while(hd+1<=tl&&(yy(que[tl])-yy(que[tl-1]))*(xx(i)-xx(que[tl]))>=(yy(i)-yy(que[tl]))*(xx(que[tl])-xx(que[tl-1])))
37            tl--;
38         que[++tl]=i;
39     }
40     printf("%lld\n",f[n]);
41     return 0;
42 }
43 

posted @ 2018-09-24 22:31  guapisolo  阅读(118)  评论(0编辑  收藏  举报