zoukankan      html  css  js  c++  java
  • HDU6438 Buy and Resell

    优先队列 + 思维

    首先有一个很自然的贪心策略就是在价格便宜的地方买入,在价格贵地方卖出,而且差值越大越好。

    关键是在什么时候卖。

    其实对于这种买入和卖出价格一样的情况,中间商是没有差价的。

    拿 1,2,10来说,我们用在2处卖出1,得到利润1,这时如果我们把2当成中间商,在10把我们从1买来的商品卖出,得到的利润是1+8=9。

    这和我们在3处卖处1的利润是一样的。

    所以我们可以用最小堆维护当前最便宜的商品,只要发现价格大于队顶,就计算利润,在让新的商品进队两次。一次作为他自己本身,另一次当成中间商。

    为了计算次数,我们要记录作为中间商的商品数量,优先使用中间商,当转卖的时候可不计算交易次数。

    #include <bits/stdc++.h>
    #define INF 0x3f3f3f3f
    #define full(a, b) memset(a, b, sizeof a)
    #define FAST_IO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
    using namespace std;
    typedef long long ll;
    inline int lowbit(int x){ return x & (-x); }
    inline int read(){
        int ret = 0, w = 0; char ch = 0;
        while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
        while(isdigit(ch)) ret = (ret << 3) + (ret << 1) + (ch ^ 48), ch = getchar();
        return w ? -ret : ret;
    }
    inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
    inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
    template <typename T>
    inline T max(T x, T y, T z){ return max(max(x, y), z); }
    template <typename T>
    inline T min(T x, T y, T z){ return min(min(x, y), z); }
    template <typename A, typename B, typename C>
    inline A fpow(A x, B p, C lyd){
        A ans = 1;
        for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
        return ans;
    }
    
    int _, n;
    int main(){
    
        for(_ = read(); _; _ --){
            n = read();
            ll ans = 0, cnt = 0;
            priority_queue< int, vector<int>, greater<int> > pq;
            map<int, int> vis;
            for(int i = 1; i <= n; i ++){
                int val = read();
                if(pq.empty() || (!pq.empty() && pq.top() >= val)){
                    pq.push(val);
                }
                else{
                    if(vis[pq.top()] == 0) cnt ++;
                    else vis[pq.top()] --;
                    ans += val - pq.top(), vis[val] ++;
                    pq.pop(), pq.push(val), pq.push(val);
                }
            }
            printf("%lld %lld
    ", ans, cnt * 2);
        }
        return 0;
    }
    
  • 相关阅读:
    剑指offer系列——56.删除链表中重复的结点
    剑指offer系列——55.链表中环的入口结点
    剑指offer系列——54.字符流中第一个不重复的字符
    剑指offer系列——53.表示数值的字符串
    MinGW与Cygwin
    Android-x86虚拟机安装配置全攻略
    linux下使用NFS挂载文件系统
    ubuntu 64bit “arm-linux-gcc: No such file or directory”问题的解决方法
    虚拟机下ubuntu的minicom使用指南
    Linux 下编译、安装、配置 QT
  • 原文地址:https://www.cnblogs.com/onionQAQ/p/11177368.html
Copyright © 2011-2022 走看看