HDU 6438 Buy and Resell(贪心+优先队列+set)

256 篇文章 0 订阅
142 篇文章 0 订阅

Description

n n n个城市,第 i i i个城市商品价格为 a i a_i ai,从 1 1 1城市出发依次经过这 n n n个城市到达 n n n城市,在每个城市可以把手头商品出售也可以至多买一个商品,问最大收益以及在最大收益下的最少交易次数

Input

第一行一整数 T T T表示用例组数,每组用例首先输入一整数 n n n表示城市数量,之后输出 n n n个整数 a i a_i ai表示每个城市商品单价

( 1 ≤ T ≤ 250 , 1 ≤ n ≤ 1 0 5 , ∑ n ≤ 5 ⋅ 1 0 5 ) (1\le T\le 250,1\le n\le 10^5,\sum n\le 5\cdot 10^5) (1T250,1n105,n5105)

Output

输出最大收益以及在最大收益下的最少交易次数

Sample Input

3
4
1 2 10 9
5
9 5 9 10 5
2
2 1

Sample Output

16 4
5 2
0 0

Solution

贪心,用优先队列维护当前位置之前所有的商品价格,每次选取价格最低的买入,如果该价格的商品之前是卖出的状态,那么就合并这四次交易变成两次交易,需要用一个 m u l s e t mulset mulset维护卖出状态的商品,时间复杂度 O ( n l o g n ) O(nlogn) O(nlogn)

Code

#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;
#define maxn 100005
int T,n,a[maxn];
priority_queue<int,vector<int>,greater<int> >que;
multiset<int>s;
multiset<int>::iterator it;
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		for(int i=1;i<=n;i++)scanf("%d",&a[i]);
		s.clear();
		while(!que.empty())que.pop();
		ll ans=0;
		int num=0;
		for(int i=1;i<=n;i++)
		{
			if(!que.empty()&&que.top()<a[i])
			{
				int x=que.top();
				que.pop();
				it=s.find(x);
				if(it==s.end())num+=2;
				else que.push(x),s.erase(it);
				ans+=a[i]-x;
				s.insert(a[i]);
			}
			que.push(a[i]);
		}
		printf("%lld %d\n",ans,num);
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值