zoukankan      html  css  js  c++  java
  • CF865D Buy Low Sell High 题解 贪心

    题目链接:https://www.luogu.com.cn/problem/CF865D

    题解完全参照自 SJC_03大佬的博客

    这里有一个我思考了很久的问题(大佬一眼就能看出来):

    假设堆顶元素是 (p_i),当前元素是 (p_j(p_j gt p_i)),则将 (p_j - p_i) 加入答案同时将 (p_j) 入堆,那为什么还需要将 (p_j) 在此入堆,这不是入堆两次了么?

    是这样的,入堆两次保证第 (j) 天最终是卖的,接下来用到过一次 (p_j) 说明第 (j) 天不买也不卖,用到过两次 (p_j) 说明第 (j) 天是买的。神奇!!

    示例代码:

    #include <bits/stdc++.h>
    using namespace std;
    int n, a;
    long long ans;
    priority_queue<int, vector<int>, greater<int> > que;
    int main() {
        scanf("%d", &n);
        while (n --) {
            scanf("%d", &a);
            if (!que.empty() && que.top() < a) {
                ans += a - que.top();
                que.pop();
                que.push(a);
            }
            que.push(a);
        }
        printf("%lld
    ", ans);
        return 0;
    }
    
  • 相关阅读:
    11.29
    11.28
    11.24
    11.21
    11.17
    11.15
    11.14
    11.9
    11.5
    11.3
  • 原文地址:https://www.cnblogs.com/quanjun/p/13758843.html
Copyright © 2011-2022 走看看