[CEOI2017] Building Bridges
题面
李超线段树优化
本来想学习一下斜率优化的,但发现这题用斜率优化还要套一个
不会李超线段树的可以看我的这篇博客。
其实这篇博客也有补充到这题的思路,但讲得不清晰,我再简单说一下。
看题,一眼丁真,可用
设
设
设
问题转化为已知
代码:
#include<bits/stdc++.h>
#define LL long long
#define N 100005
#define M 1000005
using namespace std;
int n;LL h[N],s[N],A[N],B[N];
int Best[M<<2];
inline LL GetY(int id,int x){return A[id]*x+B[id];}
inline bool Cmp(int id1,int id2,int x){
return GetY(id1,x)<GetY(id2,x);
}
#define ls (k<<1)
#define rs (k<<1|1)
#define mid (l+r>>1)
void Set(int k,int l,int r,int id){
Best[k]=id;if(l^r) Set(ls,l,mid,id),Set(rs,mid+1,r,id);
}
void Insert(int k,int l,int r,int id){
if(Cmp(id,Best[k],mid)) swap(id,Best[k]);
if(l==r||A[id]==A[Best[k]]) return;
if(A[id]>A[Best[k]]) Insert(ls,l,mid,id);
if(A[id]<A[Best[k]]) Insert(rs,mid+1,r,id);
}
LL Query(int k,int l,int r,int x){
if(l==r) return GetY(Best[k],x);
LL res(GetY(Best[k],x));
if(x<=mid) return min(res,Query(ls,l,mid,x));
return min(res,Query(rs,mid+1,r,x));
}
LL dp[N];
int main(){
scanf("%d",&n);
for(int i(1);i<=n;++i) scanf("%lld",&h[i]);
for(int i(1);i<=n;++i) scanf("%lld",&s[i]),s[i]+=s[i-1];
A[1]=-2*h[1];B[1]=h[1]*h[1]-s[1];Set(1,0,M,1);
for(int i(2);i<=n;++i){
dp[i]=Query(1,0,M,h[i])+h[i]*h[i]+s[i-1];
A[i]=-2*h[i];B[i]=dp[i]+h[i]*h[i]-s[i];
Insert(1,0,M,i);
}
printf("%lld\n",dp[n]);
return 0;
}