B

    传送门:http://codeforces.com/problemset/problem/867/E

    题意:根除n个股票,刚开始手里没股票。买入卖出,求出最大收益。

    解析:贪心+优先队列(从大到小)。只是让我们求最大收益,所以我们把它们全都借走而且不付钱。怎么想,我借走股票,以后如果遇到高价可以卖,那么只累加差价即可。没法盈利的,不管它们就相当于把它们还回去了。x进入队列,x1>x,那么盈利是x1-x,但是对于x来讲,还可能有更高价来卖出x,所以让x1入队列充当中间量。比如后来遇到个更高的价x2,那么总盈利就是x1-x+x2-x1==x2-x,x1没用了,取了更大的x2来代替了它。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
priority_queue<ll,vector<ll>,greater<ll> >q;
int main()
{
    ll n;
    ll ans=0;
    cin>>n;
    ll x;
    for(int i=1;i<=n;i++)
    {
        cin>>x;
        q.push(x);
        if(!q.empty()&&x>q.top())
        {
            ans+=x-q.top();
            q.pop();
            q.push(x);
        }
    }
    cout<<ans<<endl;
}
原文地址:https://www.cnblogs.com/liyexin/p/12559894.html