借鉴了两位大佬的博客: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;
}