[ABC250G] Stonks 题解

[ABC250G] Stonks Solution

更好的阅读体验戳此进入

题面

给定序列 $ P_n $ 表示 $ n $ 天里的股价,每天可以买入或卖出一股,本金无限,求最多能多少钱。

Solution

明显反悔贪心。

不失一般性,令 $ a \lt b \lt c $,则若某天存在如下决策,即买 $ a $ 卖 $ b $,那么赚的钱为 $ b - a $,而显然对于 $ a $ 来说,若买 $ a $ 卖 $ c $,那么贡献为 $ c - a \gt b - a $,差为 $ c - b $,则不难想到当买 $ a $ 卖 $ b $ 的时候再将 $ b $ 插入,此时如果存在 $ c $ 取了插入的 $ b $,其实际意义即为撤销买 $ a $ 卖 $ b $ 并改为买 $ a $ 卖 $ c $,但此时 $ b $ 天就无操作了,所以我们此时需要再额外插入一个 $ b $,表示后面若需要可以执行一次买 $ b $ 卖 $ d $ 的操作。不难想到可以用小根堆维护,假设堆顶元素为 $ top $,当前元素为 $ x $,若 $ x - top > 0 $ 那么贡献为 $ x - top $,反之将 $ x $ 压入小根堆即可。

双倍经验 CF865D Buy Low Sell High

Code

#define _USE_MATH_DEFINES
#include <bits/stdc++.h>

#define PI M_PI
#define E M_E
#define npt nullptr
#define SON i->to
#define OPNEW void* operator new(size_t)
#define ROPNEW(arr) void* Edge::operator new(size_t){static Edge* P = arr; return P++;}

using namespace std;

mt19937 rnd(random_device{}());
int rndd(int l, int r){return rnd() % (r - l + 1) + l;}
bool rnddd(int x){return rndd(1, 100) <= x;}

typedef unsigned int uint;
typedef unsigned long long unll;
typedef long long ll;
typedef long double ld;

template < typename T = int >
inline T read(void);

int N;
int P[210000];
ll ans(0);
priority_queue < pair < int, int >, vector < pair < int, int > >, greater < pair < int, int > > > cur;

int main(){
    N = read();
    for(int i = 1; i <= N; ++i){
        P[i] = read();
        if(!cur.empty() && P[i] > cur.top().first){
            int val, idx; tie(val, idx) = cur.top(); cur.pop();
            ans += P[i] - val, cur.push({P[i], P[i]});
            if(idx)cur.push({idx, 0});
        }else cur.push({P[i], 0});
    }printf("%lld\n", ans);
    fprintf(stderr, "Time: %.6lf\n", (double)clock() / CLOCKS_PER_SEC);
    return 0;
}

template < typename T >
inline T read(void){
    T ret(0);
    int flag(1);
    char c = getchar();
    while(c != '-' && !isdigit(c))c = getchar();
    if(c == '-')flag = -1, c = getchar();
    while(isdigit(c)){
        ret *= 10;
        ret += int(c - '0');
        c = getchar();
    }
    ret *= flag;
    return ret;
}

UPD

update-2022_12_20 初稿

posted @ 2023-01-07 15:46  Tsawke  阅读(13)  评论(0编辑  收藏  举报