1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include<iostream> #include<cstdio> #include<cstring> using namespace std; using ll=long long; const int N=5e5+10,M=1e6+10; const ll INF=1e18; template<class T> inline void read(T &x) { x=0;bool f=0; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();} while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); if(f)x=~x+1; } template<class T,class ...T1> inline void read(T &x,T1 &...x1) { read(x),read(x1...); } template<class T> inline void ckmin(T &x,T y){x=x<y?x:y;}; int n; int h[N]; ll sum[N],f[N];
struct Seg { struct Line{ll k,b;ll f(ll x){return k*x+b;}}a[N]; struct Node { int l,r; int s; }tr[M<<2]; ll f(int i,ll pos){return a[i].f(pos);} void add(int i,ll k,ll b) { a[i].k=k,a[i].b=b; modify(1,i); } void build(int x,int l,int r) { tr[x].l=l,tr[x].r=r,tr[x].s=0; if(l==r)return ; int mid=l+r>>1; build(x<<1,l,mid),build(x<<1|1,mid+1,r); } void modify(int x,int p) { if(tr[x].l==tr[x].r) if(f(p,tr[x].l)<f(tr[x].s,tr[x].l)) return tr[x].s=p,void(); int mid=tr[x].l+tr[x].r>>1; if(f(p,mid)<f(tr[x].s,mid))swap(p,tr[x].s); if(f(p,tr[x].l)<f(tr[x].s,tr[x].l))return modify(x<<1,p); if(f(p,tr[x].r)<f(tr[x].s,tr[x].r))return modify(x<<1|1,p); } ll query(int x,int pos) { ll res=f(tr[x].s,pos); if(tr[x].l==tr[x].r)return res; int mid=tr[x].l+tr[x].r>>1; if(pos<=mid)ckmin(res,query(x<<1,pos)); else ckmin(res,query(x<<1|1,pos)); return res; } }t; inline ll K(int i){return -2*h[i];} inline ll B(int i){return f[i]+1ll*h[i]*h[i]-sum[i];}
int main() { read(n); for(int i=1;i<=n;i++)read(h[i]); for(int i=1;i<=n;i++)read(sum[i]),sum[i]+=sum[i-1]; memset(f,0x3f,sizeof(f)); f[1]=0; t.build(1,0,M-10); t.a[0].b=INF; for(int i=2;i<=n;i++) { t.add(i-1,K(i-1),B(i-1)); f[i]=t.query(1,h[i])+1ll*h[i]*h[i]+sum[i-1]; } printf("%lld\n",f[n]); return 0; }
|