斜率优化实现初步(8) [LOJ][10192] [CEOI2004]锯木厂选址

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

#define int long long
const int MAXN=2e5+2333;
int n,w[MAXN],d[MAXN];
int sum[MAXN],pre[MAXN],dis[MAXN];
int f[3][MAXN],g[3][MAXN];
int head=1,tail=1,q[MAXN];

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[1][j]-g[1][k])/(pre[j]-pre[k]);
}

signed main(){
    n=read();
    for (int i=1;i<=n;i++){
        w[i]=read(),d[i]=read();
        dis[i+1]=dis[i]+d[i],pre[i]=pre[i-1]+w[i];
        sum[i]=sum[i-1]-dis[i]*w[i];
        f[1][i]=sum[i]+pre[i]*dis[i];
        g[1][i]=f[1][i]-sum[i];
    }
    for (int i=1;i<=n;i++){
        while (head<tail&&slope(q[head+1],q[head])<dis[i])
            head++;
        f[2][i]=f[1][q[head]]+sum[i]-sum[q[head]]+(pre[i]-pre[q[head]])*dis[i];
        g[2][i]=f[2][i]-sum[i];
        while (head<tail&&slope(i,q[tail])<slope(q[tail],q[tail-1]))
            tail--;
        q[++tail]=i;
    }
    int ans=0x3f3f3f3f3f3f3f3f;
    for (int i=1;i<=n;i++)
        ans=min(ans,f[2][i]+sum[n]-sum[i]+(pre[n]-pre[i])*dis[n+1]);
    printf("%lld\n",ans);
    return 0;
}

 

posted @ 2018-08-26 10:34  QingCai_DCF  阅读(140)  评论(0编辑  收藏  举报