HDU 6438 Buy and Resell (贪心)

题意
给你 n {n} 天,一些物品,第 i {i} 天的价值是 a [ i ] {a[i]} ,你可以选择在某天买进物品,在他之后的某天卖出物品,问你卖出物品利润的最大值是多少,同时保证交易次数最小。
思路
这道题按照贪心的思路去写的话就是我们在最低点买入,在最高点卖出,但是手推两个例子其实发现我们这个值是可以传递的,比如说 1 , 2 , 10 {1,2,10} 我先卖 1 {1} 2 {2} 买和之后在买 2 {2} 10 {10} 买得到的权值是 1 + 8 = 10 {1+8 = 10} 和 我在 1 {1} 买在 10 {10} 买的值是一样的,所以我们就可以维护一个小根堆,如果当前输入的值比我们的堆顶要小的话我们就把它卖掉,之后我们把这个值放到小根堆里两次,为什么是两次?第一次放的时候其实就是他本身,第二次的时候我们放的其实就是他传递的值。还有一个条件是保证交易次数最小,那么这种情况我们怎么处理呢?就是对于交易次数最小的话,那么我们就优先使用传递出来的值,因为emmm为什么?用心去感受一下,应该比较好理解的。
代码

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int maxn = 1e5+10;
int a[maxn];
typedef pair<int,int>PII;

map<int,int>M;
signed main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		priority_queue<int,vector<int>,greater<int> >que;
		M.clear();
		int n;
		scanf("%d",&n);
		int t;
		int num = 0 , ans = 0;
		for(int i = 0 ; i < n ; i ++)
		{
			scanf("%d",&t);
			if(que.empty() || que.top() >= t) que.push(t);
			else 
			{
				num++;
				int x = que.top();que.pop();
				ans += (t-x);
				if(M[x])
				{
					M[x]--;
					num--;
				}
				M[t]++;
				que.push(t);
				que.push(t);
			}
		}
		cout<<ans<<" "<<num*2<<endl; // 买一次卖一次所以要乘2 
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wjmwsgj/article/details/82185292