Codeforces-Codeforces Round #437 (Div. 2, based on MemSQL Start[c]UP 3.0 - Round 2)-E. Buy Low Sell

思路:很巧妙的贪心+优先队列。对于每天的股票,可以预先将其加入优先队列Q(小的优先),只要遇到较大的就卖掉,但是不一定是最终卖出价格,例如 3 6 7 12,按照贪心 以3买6卖,7买13卖的收入为8 ,但以 3买7卖,6买12卖则为10,因此可以将a[i]入两次队列,这样就可以通过两个6来达到最佳收入10。

Code :

#include<iostream>
#include<queue>
using namespace std;
typedef long long LL;

int n;
priority_queue<int,vector<int>,greater<int>> Q;

int main()
{
	ios::sync_with_stdio(false);
	cin>>n;
	LL ans=0;
	for(int i=0,x;i<n;++i)
	{
		cin>>x;
		Q.push(x);	Q.push(x);
		ans+=x-Q.top();	Q.pop();
	}
	cout<<ans<<endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/C_13579/article/details/81368068
今日推荐