zoukankan      html  css  js  c++  java
  • 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 << '
    ';}
    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;
    }
    
  • 相关阅读:
    FreeRTOS 任务栈大小确定及其溢出检测
    FreeRTOS任务优先级说明
    leetcode 263 Ugly Number
    L2,breakfast or lunch
    Redis(2)用jedis实现在java中使用redis
    L1,a private conversation
    Redis(1)在windows环境下的安装和测试
    springMVC的拦截器工作流程
    求交集,差集,并集,善用java的set
    java下发电子邮件demo
  • 原文地址:https://www.cnblogs.com/zwfymqz/p/10200409.html
Copyright © 2011-2022 走看看