CodeForces 867E Buy Low Sell High 思维,贪心

CodeForces 867E

题意:一支股票,你知道它接下来 n 天的价格,每一天你要么买入一股,要么卖掉一股(如果有的话),要么什么都不做。一开始没有股份,要求 n 天结束后,手上也不能有股份,问最大获利。

tags:好难想到。。。

虽然题目说每天只能进行一种操作,但为了更好计算,我们每天都假设买入一股,用堆维护。

如果前面有小于它的价格,就在今天卖掉一股,再买入一股,后面如果有更优的,那今天的就相当于是中间的价。

#include<bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
#define rep(i,a,b) for (int i=a; i<=b; ++i)
#define per(i,b,a) for (int i=b; i>=a; --i)
#define mes(a,b)  memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define MP make_pair
#define PB push_back
#define fi  first
#define se  second
typedef long long ll;
const int N = 200005;

priority_queue<int, vector<int>, greater<int >  > q;
int n, pi;
int main()
{
    scanf("%d", &n);
    ll  ans=0;
    rep(i,1,n)
    {
        scanf("%d", &pi);
        if(!q.empty() && q.top()<pi)
        {
            ans += (pi-q.top());
            q.pop();
            q.push(pi);
        }
        q.push(pi);
    }
    printf("%lld
", ans);

    return 0;
}
原文地址:https://www.cnblogs.com/sbfhy/p/7661680.html