# bzoj3437小P的牧场 斜率优化dp

## 3437: 小P的牧场

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 1542  Solved: 849
[Submit][Status][Discuss]

4
2424
3142

## Sample Output

9

1<=n<=1000000, 0 < a i ,bi < = 10000

## Source

KpmCup#0 By Greens

f[i]表示在i建立一个控制站节省的最大代价
f[i]=f[j]-a[i]-sum[i]*(j-i) j>i

 1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cmath>
5 #include<cstdlib>
6 #include<algorithm>
7 #include<queue>
8 #define ll long long
9 #define inf 9000000000000000000
10 #define MAX 1000000000000000000LL
11 using namespace std;
13 {
14     int x=0,f=1;char ch=getchar();
15     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
16     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
17     return x*f;
18 }
19 int n;
20 int l=1,r;
21 ll a[1000005],b[1000005];
22 int q[1000005];
23 ll tot,ans,f[1000005],sum[1000005];
24 double cal(int j,int k)
25 {
26     return (double)(f[k]-f[j])/(double)(j-k);
27 }
28 int main()
29 {
33     for(int i=1;i<=n;i++)sum[i]=sum[i-1]+b[i];
34     for(int i=1;i<n;i++)
35         tot+=b[i]*(n-i);
36     tot+=a[n];
37     q[++r]=n;
38     for(int i=n-1;i;i--)
39     {
40         while(l<r&&cal(q[l],q[l+1])>sum[i])l++;
41         int j=q[l];
42         f[i]=f[j]+sum[i]*(j-i)-a[i];
43         ans=max(ans,f[i]);
44         while(l<r&&cal(q[r],i)>cal(q[r-1],q[r]))r--;
45         q[++r]=i;
46     }
47     printf("%lld",tot-ans);
48     return 0;
49 }

If you live in the echo,
your heart never beats as loud.

posted @ 2017-12-27 19:43  _wsy  阅读(125)  评论(0编辑  收藏  举报