传送门
斜率优化dp
斜率方程:slope(a,b)=(f(a)-f(b))/(y(b+1)-y(a+1))
代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
inline int read(){
int x=0;char ch=' ';int f=1;
while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
if(ch=='-'){
f=-1;ch=getchar();
}
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*f;
}
int n,tot;
ll x[50001],y[50001],f[50001];
int q[50001],l,r;
inline double slope(int a,int b){
return (double)(f[a]-f[b])/(double)(y[b+1]-y[a+1]);
}
struct node{
int x,y;
inline bool operator < (const node& b) const {
return (x==b.x)?y<b.y:x<b.x;
}
}a[50001];
int main(){
n=read();
for(int i=1;i<=n;i++){
a[i].x=read();a[i].y=read();
}
sort(a+1,a+n+1);
for(int i=1;i<=n;i++){
while(tot&&y[tot]<=a[i].y)tot--;
x[++tot]=a[i].x;y[tot]=a[i].y;
}
l=0,r=0;
for(int i=1;i<=tot;i++){
while(l<r&&slope(q[l],q[l+1])<x[i])l++;
f[i]=f[q[l]]+y[q[l]+1]*x[i];
while(l<r&&slope(q[r],i)<slope(q[r-1],q[r]))r--;
q[++r]=i;
}
printf("%lld",f[tot]);
return 0;
}
本文介绍了一种使用斜率优化的动态规划算法,通过构造斜率方程来提高DP算法效率。具体展示了如何通过斜率优化减少计算量,并提供了一个完整的代码示例,帮助读者更好地理解和实现斜率优化DP。
&spm=1001.2101.3001.5002&articleId=78141603&d=1&t=3&u=d432fd6991af4c1e990b5e781a3bb48a)
563

被折叠的 条评论
为什么被折叠?



