BZOJ1597: [Usaco2008 Mar]土地购买(dp 斜率优化)
生活随笔
收集整理的這篇文章主要介紹了
BZOJ1597: [Usaco2008 Mar]土地购买(dp 斜率优化)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題意
題目鏈接
Sol
重新看了一遍斜率優(yōu)化,感覺(jué)又有了一些新的認(rèn)識(shí)。
首先把土地按照\((w, h)\)排序,用單調(diào)棧處理出每個(gè)位置第向左第一個(gè)比他大的位置,顯然這中間的元素是沒(méi)用的
設(shè)\(f[i]\)表示買(mǎi)了前\(i\)塊土地的最小花費(fèi)
\(f[i] = min_{j = 0}^{i - 1}(f[j] + w[i] * h[j + 1])\)
斜率優(yōu)化一下
// 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;
}
轉(zhuǎn)載于:https://www.cnblogs.com/zwfymqz/p/10200409.html
總結(jié)
以上是生活随笔為你收集整理的BZOJ1597: [Usaco2008 Mar]土地购买(dp 斜率优化)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: gui开头的成语有哪些?
- 下一篇: 有原型的对象和没有原型的对象