BZOJ1597: [Usaco2008 Mar]土地购买(dp 斜率优化)
题意
Sol
重新看了一遍斜率优化,感觉又有了一些新的认识。
首先把土地按照\((w, h)\)排序,用单调栈处理出每个位置第向左第一个比他大的位置,显然这中间的元素是没用的
设\(f[i]\)表示买了前\(i\)块土地的最小花费
\(f[i] = min_{j = 0}^{i - 1}(f[j] + w[i] * h[j + 1])\)
斜率优化一下
// luogu-judger-enable-o2
#include<bits/stdc++.h>
#define Pair pair<int, int>
#define MP(x, y) make_pair(x, y)
#define fi first
#define se second
#define int long long
#define LL long long
#define pt(x) printf("%d ", x);
#define Fin(x) {freopen(#x".in","r",stdin);}
#define Fout(x) {freopen(#x".out","w",stdout);}
using namespace std;
const int MAXN = 1e6 + 10, mod = 1e9 + 7;
LL INF = 6e18 + 10;
const double eps = 1e-9;
template <typename Y> inline void chmin(Y &a, Y b){a = (a < b ? a : b);}
template <typename Y> inline void chmax(Y &a, Y b){a = (a > b ? a : b);}
template <typename Y> inline void debug(Y a){cout << a << '\n';}
int sqr(int x) {return x * x;}
int add(int x, int y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
void add2(int &x, int y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
int mul(int x, int y) {return 1ll * x * y % mod;}
inline int read() {
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int N, cur, q[MAXN];
LL f[MAXN];
struct Node {
int w, h;
bool operator < (const Node &rhs) const {
return w == rhs.w ? h < rhs.h : w < rhs.w;
}
}a[MAXN];
double Y(int x) {
return f[x];
}
double X(int x) {
return -a[x + 1].h;
}
double slope(int a, int b) {
return double(Y(b) - Y(a)) / (X(b) - X(a));
}
signed main() {
N = read();
for(int i = 1; i <= N; i++) a[i].w = read(), a[i].h = read();
sort(a + 1, a + N + 1);
for(int i = 1; i <= N; i++) {
while(cur && a[i].h >= a[cur].h) cur--;
a[++cur] = a[i];
}
for(int i = 1; i <= cur; i++) f[i] = INF;
q[1] = 0;
for(int i = 1, h = 1, t = 1; i <= cur; i++) {
while(h < t && slope(q[h], q[h + 1]) < a[i].w) h++;
f[i] = (LL) f[q[h]] + 1ll * a[i].w * a[q[h] + 1].h;
while(h < t && slope(q[t], i) < slope(q[t - 1], q[t])) t--;
q[++t] = i;
}
cout << f[cur];
return 0;
}
作者:自为风月马前卒
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。