首页 > 代码库 > 【bzoj 1597】[Usaco2008 Mar]土地购买

【bzoj 1597】[Usaco2008 Mar]土地购买

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 plot. 每组的价格分别为100,100,300, 总共500.

 

安利一篇博客……

刚接触斜率优化dp时就是看着这篇博客看懂的>_<

 

技术分享
 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 using namespace std;
 5 const int N=50050;
 6 int n,cnt,q[N];
 7 long long x[N],y[N],f[N];
 8 struct node{long long x,y;}a[N];
 9 bool cmp(node a,node b){return a.x==b.x?a.y<b.y:a.x<b.x;}
10 long long read()
11 {
12     long long x=0,f=1;char c=getchar();
13     while(c<0||c>9){if(c==-)f=-1;c=getchar();}
14     while(c>=0&&c<=9){x=x*10+c-0;c=getchar();}
15     return x*f;
16 }
17 double slope(int k,int j){return (double)(f[j]-f[k])/(y[k+1]-y[j+1]);}
18 int main()
19 {
20     n=read();
21     for(int i=1;i<=n;i++)
22         a[i].x=read(),a[i].y=read();
23     sort(a+1,a+n+1,cmp);
24     for(int i=1;i<=n;i++)
25     {
26         while(cnt&&a[i].y>=y[cnt])cnt--;
27         x[++cnt]=a[i].x;y[cnt]=a[i].y;
28     }
29     int l=0,r=0;
30     for(int i=1;i<=n;i++)
31     {
32         while(l<r&&slope(q[l],q[l+1])<x[i])l++;
33         int t=q[l];
34         f[i]=f[t]+y[t+1]*x[i];
35         while(l<r&&slope(q[r-1],q[r])>slope(q[r],i))r--;
36         q[++r]=i;
37     }
38     printf("%lld",f[cnt]);
39     return 0;
40 }
View Code

 

【bzoj 1597】[Usaco2008 Mar]土地购买