BZOJ 1096: [ZJOI2007]仓库建设 | 斜率优化DP

题目:

http://www.lydsy.com/JudgeOnline/problem.php?id=1096


题解:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1e6+5;
typedef long long ll;
int n,q[N];
ll dp[N],c[N],x[N],p[N],sump[N],sumpx[N];
double calc(int k,int j)
{
    return 1.0*(dp[j]-dp[k]+sumpx[j]-sumpx[k])/(sump[j]-sump[k]);
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%lld%lld%lld",&x[i],&p[i],&c[i]),sump[i]=sump[i-1]+p[i],sumpx[i]=sumpx[i-1]+p[i]*x[i];
    int ql=0,qr=0;
    for(int i=1;i<=n;i++)
    {
        while(ql<qr &&calc(q[ql],q[ql+1])<(double)x[i]) ql++;
        int j=q[ql];
        dp[i]=dp[j]+(sump[i]-sump[j])*x[i]-(sumpx[i]-sumpx[j])+c[i];
        while(ql<qr &&calc(q[qr-1],q[qr])>calc(q[qr],i))qr--;
        q[++qr]=i;
    }
    printf("%lld\n",dp[n]);
    return 0;
}

 

posted @ 2018-02-01 20:49  MSPqwq  阅读(54)  评论(0编辑  收藏