hdu6438Buy and Resell(贪心+优先队列)

借鉴了两位大佬的博客:https://blog.csdn.net/liufengwei1/article/details/82054532
https://blog.csdn.net/xiang_6/article/details/82054463

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6438

题意:给定n天,每天有个价格,可以买一个物品或者可以把手中的物品卖掉

分析:
维护一个优先队列,维护3个信息,那天的卖价,是否已经跟别人交换过,那天

考虑一个新的物品跟队首的比较,如果新物品比队首还小,说明交易亏本,直接丢入堆中,否则就交易,如果队首的元素是已经跟之前交易过的,那么就相当于当前物品和之前那个交易,然后队首就变成没有交易了,继续压入队列中,交换次数不变,如果队首是没有交易过的,那么就交易,交易次数+2.把当前物品压入队列中。

代码:

#include<iostream>
#include <cstdio>
#include<algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <stack>
#include <bitset>

using namespace std;
typedef pair<int,int> P;
typedef long long ll;

const int maxn = 1e5 + 7;
const ll mod = 1e9 + 7;
map<int,int> vis;

int main() {
  int T;
  scanf("%d", &T);
  while(T--) {
    int n;
    scanf("%d", &n);
    priority_queue<int, vector<int>, greater<int> > qu;
    while(!qu.empty()) qu.pop();
    ll ans = 0, cnt = 0;
    vis.clear();
    for(int i = 1; i <= n; ++i) {
      int x; scanf("%d", &x);
      if(qu.empty() || qu.top() >= x) {
        qu.push(x);
      }
      else {
        cnt++;
        int t = qu.top(); qu.pop();
        ans += (x-t);
        if(vis[t] > 0) {
          cnt--;
          vis[t]--;
          qu.push(t);
        }
       qu.push(x);
        vis[x]++;
      }
    }
    printf("%lld %lld\n", ans, cnt*2);
  }

  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值