[CEOI2017] Building Bridges

· · 题解

题面

李超线段树优化 \text{dp}。

本来想学习一下斜率优化的,但发现这题用斜率优化还要套一个 \text{CDQ} 分治,直接放弃。

不会李超线段树的可以看我的这篇博客。

其实这篇博客也有补充到这题的思路,但讲得不清晰,我再简单说一下。

看题,一眼丁真,可用 \text{dp}。

设 dp_i 表示将 1 号与 i 号柱子连接的最小代价,随便推一推,转移方程就出来了:

dp_i=\min\limits_{1\leq j<i}\{dp_j+(h_i-h_j)^2+\sum\limits_{k=j}^iw_k\}

设 s_i=\sum\limits_{k=1}^iw_k,则有:

\begin{aligned} dp_i&=\min\limits_{0\leq j<i}\{dp_j+h_i^2+h_j^2-2h_ih_j+s_{i-1}-s_j\}\\ &=\min\limits_{0\leq j<i}\{(-2h_i)\cdot h_j+(dp_j+h_j^2-s_j)\}+h_i^2+s_{i-1}\\ \end{aligned}

设 a_j=-2h_j,b_j=dp_j+h_j^2-s_j,则有:

dp_i=\min\limits_{0\leq j<i}\{a_jh_i+b_j\}+h_i^2+s_{i-1}

问题转化为已知 i-1 条直线 y=a_jx+b_j,求 x=h_i 时的 y 的最小值。

代码:

#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;
}