# BZOJ3437: 小P的牧场（斜率优化DP）

## 3437: 小P的牧场

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 1914  Solved: 1046
[Submit][Status][Discuss]

4
2424
3142

## Sample Output

9

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

## Source

#include<bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=1000010;
ll DY(int i){ return dp[i]+X[i];}
ll getans(int i,int j){
return dp[j]+a[i]+(sum[i]-sum[j])*i-(X[i]-X[j]);
}
int main()
{
scanf("%d",&N);
rep(i,1,N) scanf("%d",&a[i]);
rep(i,1,N) scanf("%d",&b[i]);
rep(i,1,N) {
sum[i]=sum[i-1]+b[i];
X[i]=X[i-1]+1ll*b[i]*i;
}
rep(i,1,N){
while(top>0&&(DY(i)-DY(q[top]))*(sum[i]-sum[q[top-1]])<(DY(i)-DY(q[top-1]))*(sum[i]-sum[q[top]])) top--;
q[++top]=i;
}
printf("%lld\n",dp[N]);
return 0;
}

#include<bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=1000010;
ll a[maxn],b[maxn],q[maxn],top,N; ll X[maxn],sum[maxn],dp[maxn];
ll DY(int i){ return dp[i]+X[i];}
ll getans(int i,int j){
return dp[j]+a[i]+(sum[i]-sum[j])*i-(X[i]-X[j]);
}
int main()
{
scanf("%lld",&N);
rep(i,1,N) scanf("%lld",&a[i]);
rep(i,1,N) scanf("%lld",&b[i]);
rep(i,1,N) {
sum[i]=sum[i-1]+b[i];
X[i]=X[i-1]+b[i]*i;
}
rep(i,1,N){
int L=0,R=top,Mid,pos=top;
while(L<=R){
Mid=(L+R)>>1;
if(getans(i,q[Mid])<=getans(i,q[Mid+1])) pos=Mid,R=Mid-1;
else L=Mid+1;
}
dp[i]=getans(i,q[pos]);
while(top>0&&(DY(i)-DY(q[top]))*(sum[i]-sum[q[top-1]])<(DY(i)-DY(q[top-1]))*(sum[i]-sum[q[top]])) top--;
q[++top]=i;
}
printf("%lld\n",dp[N]);
return 0;
}
View Code

It is your time to fight！
posted @ 2018-11-21 20:41  nimphy  阅读(196)  评论(0编辑  收藏  举报