斜率优化实现初步(6) [BZOJ][3437]小P的牧场
#include<bits/stdc++.h> using namespace std; #define int long long const int MAXN=1e6+23333; int n; int a[MAXN],b[MAXN],sum[MAXN],pre[MAXN]; int f[MAXN],g[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[j]-g[k])/(pre[j]-pre[k]); } signed main(){ n=read(); for (int i=1;i<=n;i++) a[i]=read(); for (int i=1;i<=n;i++) b[i]=read(),sum[i]=sum[i-1]-i*b[i],pre[i]=pre[i-1]+b[i]; for (int i=1;i<=n;i++){ while (head<tail&&slope(q[head+1],q[head])<i) head++; f[i]=f[q[head]]+sum[i]-sum[q[head]]+(pre[i]-pre[q[head]])*i+a[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; }