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

来源:互联网 发布:腾讯视频下载mac版 编辑:程序博客网 时间:2024/05/18 09:15

传送门
斜率优化dp
斜率方程:slope(a,b)=(f(a)-f(b))/(y(b+1)-y(a+1))
代码:

#include<bits/stdc++.h>#define ll long longusing 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;}
阅读全文
0 0
原创粉丝点击