斜率优化Dp
前置芝士
- 单调队列优化
- 斜率
- 上凸壳和下凸壳
斜率优化DP适用于什么时候
斜率优化DP一般适用于满足如下所有情况的题目:
1.区间dp
2.含有类似
接下来我就直接讲题目了,因为斜率Dp因题而异
例题
题目传送门
本题的
#pragma G++ optimize(3,"Ofast","inline")
#include <iostream>
#define int long long
#define N 1000003
inline int max(const int &x, const int &y){return x > y ? x : y;}
inline int min(const int &x, const int &y){return x < y ? x : y;}
inline int read(){int x = 0, f = 1; char ch = getchar(); while(ch > 57 || ch < 48){if(ch == 45)f = -1; ch = getchar();}while(ch >= 48 && ch <= 57){x = (x<<1) + (x<<3) + (ch^48); ch = getchar();} return x * f;}
int a,n,b,c,f[N],s[N];
inline void solve(){
n=read(),a=read(),b=read(),c=read();
for(int i=1;i<=n;++i)s[i]=s[i-1]+read();//a没有用处,直接用s代替
for(int i=1;i<=n;++i){
f[i]=-1e18;//哈基米·初始化
for(int j=0;j<i;++j)f[i]=max(f[i],f[j]+a*(s[i]-s[j])*(s[i]-s[j])+b*(s[i]-s[j])+c);//dp状态转移方程:f[i]=min(f[j]+a*(s[i]-s[j])^2+b*(s[i]-s[j])+c);
}
printf("%lld\n",f[n]);//哈基米·输出
}
signed main(){
//freopen(".in","r",stdin),freopen(".out","w",stdout);
solve();//哈基米·初始函数
return 0;
}
dp状态转移方程为
假设找到了一个最优的
我们将柿子变成一个崭新的柿子,首先先将常数和所有带有
我们发现柿子很像一次函数
我们设
那
我们把(x,y)构成一个直角坐标系,如下图所示
<img src="https://cdn.luogu.com.cn/upload/image_hosting/9vs0h32w.png" style="zoom: 33%;" />
我们因为要求最大值,所以要维护一个下凸壳,我们还知道斜率可以判断是否为上下凸壳,那我们就可以用单调队列维护斜率,如果新的点加进来形成的不是正确的下凸壳,那便把前面的点删掉,要保证答案为一个下凸壳,再把不可能为答案的点,也就是过时的点删掉,如果还有看不懂的可以看代码
#pragma G++ optimize(3,"Ofast","inline")
#include <iostream>
#define int long long
#define eps 1e-9
//防止除以0
#define N 1000003
inline int max(const int &x, const int &y){return x > y ? x : y;}
inline int min(const int &x, const int &y){return x < y ? x : y;}
inline int read(){int x = 0, f = 1; char ch = getchar(); while(ch > 57 || ch < 48){if(ch == 45)f = -1; ch = getchar();}while(ch >= 48 && ch <= 57){x = (x<<1) + (x<<3) + (ch^48); ch = getchar();} return x * f;}
int n,s[N],f[N],st[N],h,t,a,b,c;
inline double slope(int i,int j){
return (((f[i]+a*s[i]*s[i]-b*s[i])-(f[j]+a*s[j]*s[j]-b*s[j]))*1.0/(s[i]==s[j]?eps:s[i]-s[j]));
}//斜率slope=(y[i]-y[j])/(x[i]-x[j]),要保证x[i]!=x[j]
inline void solve(){
n=read(),a=read(),b=read(),c=read();
for(int i=1;i<=n;++i)s[i]=s[i-1]+read();
h=1;
//哈基米·初始化·输入
for(int i=1;i<=n;++i){
while(h<t&&slope(i-1,st[t])>slope(st[t],st[t-1]))--t;//保证图形是一个下凸壳
st[++t]=i-1;//哈基米·新点入栈
while(h<t&&slope(st[h+1],st[h])>2*a*s[i])++h;//将前面几个不可能是答案也就是已经过时的点删除
int j=st[h];
f[i]=f[j]+a*(s[i]-s[j])*(s[i]-s[j])+b*(s[i]-s[j])+c;//哈基米·计算答案
}
printf("%lld\n",f[n]);//哈基米·输出答案
}
signed main(){
//freopen(".in","r",stdin),freopen(".out","w",stdout);
solve();//哈基米·函数
return 0;
}
以上就是我对于斜率DP的所有理解,若有新的想法可以洛谷私信我,或加我微信(wxid_hu5lz543ozuz22)