BZOJ 1096: [ZJOI2007]仓库建设(动态规划+斜率优化)

第一次写斜率优化,发现其实也没啥难的,没打过就随便找了一份代码借(chao)鉴(xi)下,不要介意= =

题解实在是懒得写了,贴代码吧= =

CODE:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 1000010
long long f[maxn],x[maxn],sum[maxn],sum1[maxn],q[maxn];
int c[maxn];
int n;
long long m(int x1,int y1){
    return (f[x1]-sum1[x1]+sum[x1]*x[x1])-(f[y1]-sum1[y1]+sum[y1]*x[y1]);
}
int main(){
    scanf("%d",&n);
    for (int i=1;i<=n;i++) {
 int y;
 scanf("%d%d%d",&x[i],&y,&c[i]);
 sum[i]=sum[i-1]+y;
 sum1[i]=sum1[i-1]+sum[i-1]*(x[i]-x[i-1]);
    }
    q[1]=0;
    int h=1,t=1;
    f[0]=0;
    for (int i=1;i<=n;i++) {
 while (h<t&&m(q[h+1],q[h])<=x[i]*(sum[q[h+1]]-sum[q[h]])) h++;
 f[i]=c[i]+f[q[h]]+sum1[i]-sum1[q[h]]-sum[q[h]]*(x[i]-x[q[h]]);
 while (h<t&&m(i,q[t])*(sum[q[t]]-sum[q[t-1]])<=m(q[t],q[t-1])*(sum[i]-sum[q[t]])) t--;
 q[++t]=i;
    }
    printf("%lld",f[n]);
    return 0;
}

posted @ 2014-07-07 20:55  New_Godess  阅读(39)  评论(0编辑  收藏