码迷,mamicode.com
首页 > 其他好文 > 详细

2016vijos 1-2 股神小L(堆)

时间:2018-04-27 23:03:35      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:分享   char   include   mes   image   http   技术分享   name   else   

技术分享图片

 

维护前i天的最优解,那么在后面可能会对前面几天的买卖情况进行调整

如果前面买入,买入的这个在后面一定不会卖出

如果前面卖出,卖出的这个可能会在后面变成买入,因为买这个,卖后面的会获得更多的收益

用一个小根堆,存储前面所有的卖出的股票的价格

如果后面想卖出,扔到堆里

如果后面想买入,与堆顶元素比较,如果堆顶大,那就买入;如果堆顶小,那就把堆顶的卖出改为买入,后面那个卖出

即能卖就暂时先卖,扔到堆里,不优再调整

#include<queue>
#include<cstdio>
#include<iostream>

using namespace std;

typedef long long LL;

priority_queue<int,vector<int>,greater<int> >q;

void read(int &x)
{
    x=0; char c=getchar();
    while(!isdigit(c)) c=getchar();
    while(isdigit(c)) { x=x*10+c-0; c=getchar(); }
}

int main()
{
    freopen("stock.in","r",stdin);
    freopen("stock.out","w",stdout);
    int n,x,y;
    LL ans=0;
    read(n);
    read(x);
    ans-=x;
    for(int i=2;i<=n;++i)
    {
        read(x);
        if(!(i&1)) 
        {
            ans+=x;
            q.push(x);
        }
        else
        {
            y=q.top();
            if(x>y)
            {
                ans+=x-y*2;
                q.pop();
                q.push(x);
            }
            else ans-=x;
        }
    }
    cout<<ans;
}

 

2016vijos 1-2 股神小L(堆)

标签:分享   char   include   mes   image   http   技术分享   name   else   

原文地址:https://www.cnblogs.com/TheRoadToTheGold/p/8964731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!