您的位置:首页 > 其它

[bzoj1597]: [Usaco2008 Mar]土地购买(斜率优化dp)

2017-09-30 12:20 495 查看
传送门

斜率优化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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: