BZOJ1597 土地购买 【dp + 斜率优化】

1597: [Usaco2008 Mar]土地购买

Time Limit: 10 Sec  Memory Limit: 162 MB
Submit: 5466  Solved: 2035
[Submit][Status][Discuss]

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
FJ分3组买这些土地:
第一组:100x1,
第二组1x100,
第三组20x5 和 15x15 plot.
每组的价格分别为100,100,300, 总共500.

我们先将所有矩形按照(x,y)排序,首先能保证x升序,再往前并掉y小于当前值的,使得x升序,y降序

这样我们设f[i]表示第i个位置最小方案,就有f[i] = min{f[j] + y[j + 1] * x[i]}

很明显斜率优化:化为-x[i] * y[j + 1] + f[i] = f[j]

维护凸包,用当前斜率-x[i]去截使得截距最小,大概是这个样子的:


单调队列维护凸包就好了

【调了一个晚上QAQ我还是太弱了】

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define eps 1e-9
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define fo(i,x,y) for (int i = (x); i <= (y); i++)
#define Redge(u) for (int k = head[u]; k != -1; k = edge[k].next)
using namespace std;
const int maxn = 50005,maxm = 100005,INF = 1000000000;
inline LL read(){
	LL out = 0,flag = 1;char c = getchar();
	while (c < 48 || c > 57) {if (c == '-') flag = -1; c = getchar();}
	while (c >= 48 && c <= 57) {out = out * 10 + c - 48; c = getchar();}
	return out * flag;
}
LL N,n;
LL f[maxn],q[maxn],l,r,X[maxn],Y[maxn];
struct node{LL x,y;}p[maxn];
inline bool operator < (const node& a,const node& b){
	return a.x == b.x ? a.y < b.y : a.x < b.x;
}
inline double slope(LL u,LL v){
	return (double)(f[u] - f[v]) / (Y[u + 1] - Y[v + 1]);
}
inline LL getf(LL i,LL j){
	return f[j] + Y[j + 1] * X[i];
}
int main()
{
	N = read();
	REP(i,N) p[i].x = read(),p[i].y = read();
	sort(p + 1,p + 1 + N); Y[n] = INF;
	for (int i = 1; i <= N; i++){
		while (n && Y[n] <= p[i].y) n--;
		X[++n] = p[i].x; Y[n] = p[i].y;
	}
	l = r = 0;
	for (int i = 1; i <= n; i++){
		while (l < r && slope(q[l],q[l + 1]) > -X[i]) l++;
		f[i] = getf(i,q[l]);
		while (l < r && slope(i,q[r]) > slope(q[r],q[r - 1])) r--;
		q[++r] = i;
	}
	cout<<f[n]<<endl;
	return 0;
}


posted @ 2017-11-27 20:06  Mychael  阅读(154)  评论(0编辑  收藏  举报