欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

BZOJ1597: [Usaco2008 Mar]土地购买(dp 斜率优化)

程序员文章站 2022-10-18 23:41:25
题意 "题目链接" Sol 重新看了一遍斜率优化,感觉又有了一些新的认识。 首先把土地按照$(w, h)$排序,用单调栈处理出每个位置第向左第一个比他大的位置,显然这中间的元素是没用的 设$f[i]$表示买了前$i$块土地的最小花费 $f[i] = min_{j = 0}^{i 1}(f[j] + ......

题意

题目链接

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;
}