BZOJ1597土地购买 【斜率优化DP】

 

BZOJ1597土地购买 【斜率优化DP】


Description

农夫John准备扩大他的农场,他正在考虑N (1 <= N <= 50,000) 块长方形的土地. 每块土地的长宽满足(1 <= 宽 <= 1,000,000; 1 <= 长 <= 1,000,000). 每块土地的价格是它的面积,但FJ可以同时购买多快土地. 这些土地的价格是它们最大的长乘以它们最大的宽, 但是土地的长宽不能交换. 如果FJ买一块3x5的地和一块5x3的地,则他需要付5x5=25. FJ希望买下所有的土地,但是他发现分组来买这些土地可以节省经费. 他需要你帮助他找到最小的经费.

Input

  • 第1行: 一个数: N
  • 第2..N+1行: 第i+1行包含两个数,分别为第i块土地的长和宽

Output

  • 第一行: 最小的可行费用.

Sample Input

4
100 1
15 15
20 5
1 100

输入解释:

共有4块土地.

Sample Output

500

HINT

FJ分3组买这些土地:
第一组:100x1
第二组1x100
第三组20x5 和 15x15
每组的价格分别为100,100,300, 总共500.


 


#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define N 50010
inline LL read(){
    LL ans=0,w=1;char c=getchar();
    while(!isdigit(c)&&c!='-')c=getchar();
    if(c=='-')c=getchar(),w=-1;
    while(isdigit(c))ans=ans*10+c-'0',c=getchar();
    return ans*w;
} 
LL n,cnt=0,f[N],q[N];
struct Node{LL x,y;}a[N],b[N];
bool cmp(Node a,Node b){
    if(a.x==b.x)return a.y<b.y;
    return a.x<b.x;
}
double get_k(LL t1,LL t2){
    return (double)(f[t1]-f[t2])/(b[t2+1].y-b[t1+1].y);
}
int main(){
    n=read();
    for(LL i=1;i<=n;i++)a[i].x=read(),a[i].y=read();
    sort(a+1,a+n+1,cmp);
    for(LL i=1;i<=n;i++){
        while(cnt&&a[i].y>=b[cnt].y)cnt--;
        b[++cnt].x=a[i].x;
        b[cnt].y=a[i].y;
    }
    LL l=0,r=0;
    for(LL i=1;i<=n;i++){
        while(l<r&&get_k(q[l],q[l+1])<b[i].x)l++;
        LL t=q[l];
        f[i]=f[t]+b[t+1].y*b[i].x;
        while(l<r&&get_k(q[r],i)<get_k(q[r-1],q[r]))r--;
        q[++r]=i;
    }
    printf("%lld",f[cnt]);
}
posted @ 2018-06-02 14:54  Dream_maker_yk  阅读(156)  评论(0编辑  收藏  举报