您的位置:首页 > 其它

codeforces865D - Buy Low Sell High

2018-01-03 18:04 459 查看
题面在这里

题意:

有n天,每天有股票,价格不全相同。

现在每天你可以选择买进一只股票,卖出一只股票,或什么也不做。

卖出一定要在有股票的前提下。

问最多可以收益多少。

做法:

你要卖出肯定是之前买的价钱要小于卖出的价钱。

于是我们可以把价钱都扔到一个小根堆里。

每次假如当前的钱大于堆顶,就把堆顶弹出,答案减去堆顶,加上当前的钱数,代表买了之前那天的股票,在今天卖出。

并且,你要把这天的钱数x push进堆两次。

对于这个操作,我们这么理解。

假如你之后有一次弹出了这个x,相当于反悔,不卖那一天卖出的股票。

假如有两次弹出了x,说明你不仅不卖那天卖出的股票,你还要再买那天的股票,然后在之后某一天卖出。

假如当前的钱小于堆顶,就直接push进堆。表示这个x要作为之后某一次卖出的股票而买进。

易错点:

小根堆你要push进它的相反数。

代码:

<
4000
code class="language-cpp hljs ">/*************************************************************
Problem: codeforces 865D - Buy Low Sell High
User: bestFy
Language: C++
Result: Accepted
Time: 46 ms
Memory: 5100 KB
Submit_Time: 2018-01-03 17:43:22
*************************************************************/

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cctype>
#include<queue>
using namespace std;
typedef long long LL;

inline LL read()
{
char ch = getchar(); LL x = 0; int op = 1;
for(; !isdigit(ch); ch = getchar()) if(ch == '-') op = -1;
for(; isdigit(ch); ch = getchar()) x = x*10 + ch-'0';
return x*op;
}

const int N = 300010;
int n;

int main()
{
scanf("%d", &n); LL ans = 0;
priority_queue<int> q;
for(int i = 1; i <= n; i ++) {
int x = read();
if(q.empty()) { q.push(-x); continue; }
if(-q.top() < x) {
ans += x + q.top(); q.pop();
q.push(-x); q.push(-x);
} else q.push(-x);
}
cout << ans;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: