斜率优化实现初步(2) [BZOJ][1096][ZJOI2007]仓库建设

#include<bits/stdc++.h>
using namespace std;

#define int long long
const int MAXN=1e6+2333;

int n;
int x[MAXN],p[MAXN],c[MAXN]
int sum[MAXN],pre[MAXN],head=1,tail=1,q[MAXN];
int f[MAXN],g[MAXN];
/*
    f[i]=min(f[j]+sum[i]-sum[j]+(pre[i]-pre[j])*x[i]+c[i])
    -> g[i]=f[j]-sum[j]
    -> slope(j,k)=(g[j]-g[k])/(pre[j]-pre[k])
    -> j is better than k if slope(j,k)<x[i]
*/

int read(){
    int x=0,f=1;char ch=getchar();
    while (!isdigit(ch)) { if (ch=='-') f=-1; ch=getchar();}
    while (isdigit(ch)) x=x*10+ch-48,ch=getchar();
    return x*f;
}

int slope(int j,int k){
    return (g[j]-g[k])/(pre[j]-pre[k]);
}

signed main(){
    n=read();
    for (int i=1;i<=n;i++){
        x[i]=read(),p[i]=read(),c[i]=read();
        sum[i]=sum[i-1]-x[i]*p[i];
        pre[i]=pre[i-1]+p[i];
    }
    for (int i=1;i<=n;i++){
        while (head<tail&&slope(q[head+1],q[head])<x[i])
            head++;
        f[i]=g[q[head]]+sum[i]+(pre[i]-pre[q[head]])*x[i]+c[i];
        g[i]=f[i]-sum[i];
        while (head<tail&&slope(i,q[tail])<slope(q[tail],q[tail-1]))
            tail--;
        q[++tail]=i;
    }
    printf("%lld\n",f[n]);
    return 0;
}

 

posted @ 2018-08-25 11:04  QingCai_DCF  阅读(138)  评论(0编辑  收藏  举报