呃,老规矩,方程、转化神马的都在代码注释里面。
不会斜率优化的移步这篇:http://blog.csdn.net/vmurder/article/details/41648159
没事闲的想看点经验的来“前一篇”http://blog.csdn.net/vmurder/article/details/41682901
代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define N 1001000 #define inf 0x3f3f3f3f #define INF 0x3f3f3f3f3f3f3f3fll /* f[i]=f[j]+sum[i]-sum[j]-b[j]*i+b[j]*j+a[i] f[j]-sum[j]+b[j]*j=i*b[j]+f[i]-sum[i]-a[i] y=f[j]-sum[j]+b[j]*j x=b[j] k=i b=f[i]-sum[i]-a[i] */ using namespace std; int n,a[N]; struct Point { long long x,y; int id; Point(long long _x,long long _y,int _id):x(_x),y(_y),id(_id){} Point(){} }now,q[N]; int l,r; long long f[N],b[N],sum[N]; inline long long xmul(Point i,Point j,Point k){return (j.y-k.y)*(i.x-k.x)-(i.y-k.y)*(j.x-k.x);} int main() { // freopen("test.in","r",stdin); // freopen("my.out","w",stdout); int i,j; scanf("%d",&n); memset(f,0x3f,sizeof(f)),f[0]=0; for(i=1;i<=n;i++)scanf("%d",&a[i]); for(i=1;i<=n;i++)scanf("%I64d",&b[i]),b[i]+=b[i-1],sum[i]=sum[i-1]+b[i-1]; for(i=1;i<=n;i++) { now=Point(b[i-1],f[i-1]-sum[i-1]+b[i-1]*i-b[i-1],i-1); while(l<r&&xmul(now,q[r],q[r-1])>=0)r--; //斜(j,k)>=斜(i,k) 弹 q[++r]=now; long long K=i; while(l<r&&q[l+1].y-q[l].y<=(q[l+1].x-q[l].x)*K)l++; j=q[l].id; f[i]=f[j]+sum[i]-sum[j]-(long long)b[j]*i+(long long)b[j]*j+a[i]; } cout<<f[n]<<endl; return 0; }