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

#include
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)*/

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 (head1],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 (head1]))
            tail--;
        q[++tail]=i;
    }
    printf("%lld\n",f[n]);
    return 0;
}

 

转载于:https://www.cnblogs.com/QingCai-DCF/p/9533243.html

你可能感兴趣的:(斜率优化实现初步(2) [BZOJ][1096][ZJOI2007]仓库建设)