[贪心]低买高卖的最大收益(优先队列)

http://acm.hdu.edu.cn/showproblem.php?pid=6438
http://codeforces.com/contest/867/problem/E
queue没有clear只能while清空

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
priority_queue<int, vector<int>, greater<int> > buy, sell;
int main()
{
    ios::sync_with_stdio(0); cin.tie(0);
    //sell.top()总是大于buy.top()
    //case 1: x > sell.top() sell.top()不卖
    //于是sell.top()又可以和buy.top()比较
    //case 2: x > buy.top() 卖了
    //case other: 买
    //优先把之前的以更高价格卖掉
    int t;
    cin >> t;
    while (t--){
    int n, x, step = 0;
    cin >> n;
    ll ans = 0;
    while (n--){
        cin >> x;
        //case 1
        if (!sell.empty() && x > sell.top()){
            //以更高价格卖出
            ans += x - sell.top();
            //先判断能不能把之前买的以sell.top()卖了
            if (!buy.empty() && sell.top() > buy.top()){
                //再卖一次
                ans += sell.top() - buy.top();
                buy.pop();
                ++step;
            }else{
                buy.push(sell.top());
                sell.pop();
            }
            //判断完毕,再把这个更高的卖出价入队
            sell.push(x);
        //case 2
        }else if (!buy.empty() && x > buy.top()){
            ans += x - buy.top();
            sell.push(x);
            buy.pop();
            ++step;
        }else buy.push(x);
    }
    cout << ans << ' ' << 2 * step << '\n';
    while (!buy.empty()) buy.pop();
    while (!sell.empty()) sell.pop();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值