反悔贪心之反悔自动机
定义
它能够自动的维护我们反悔的操作,通常适用于带限制的决策问题上。
分类
具体的反悔自动机又分为和两种。
解题思路
- 既然是需要盈利,那么只要出现了两天满足并且,那么就可以得到从第天买入,在第天卖出,此时的利润是。
- 若后面存在一天满足且。那么就可以在第天买入,在第天卖出,此时的盈利是,其满足。要是遇到了这样的就需要进行反悔。
- 若直接反悔,那么维护的信息就需要找到上次的点,但是两两组合是中情况。很难维护,因此这里想到使用一种策略来一劳永逸,已知我们之前计算了,现在又进来的贡献是,但是最优解是,我们发把上述两个贡献加起来就可以了。因此这里再计算贡献的时候要是出现了且的情况,那么就将添加到最后的答案中。
- 在上面的讨论中我们可以得到反悔的条件,即出现了且的情况。因此这里使用一个小根堆来维护所有的价值。此时堆顶是,新进来的就是。对于答案可以直接添加。之后将这个直接入堆当作新的。其中,这两天都是卖的时刻,但是新进来的这里一天是可以当作买的天的也就是,所以是需要把这一天也入堆。
#include <set>
#include <map>
#include <cmath>
#include <stack>
#include <deque>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#include <unordered_set>
#include <unordered_map>
//#define int long long
#define endl '\n'
using namespace std;
typedef long long LL;
typedef pair<LL, LL> PLL;
typedef pair<int, int> PII;
typedef unsigned long long ULL;
typedef priority_queue<LL> LBH; // LL big heap
typedef priority_queue<int> IBH; // int big heap
typedef pair<double, double> PDD;
typedef priority_queue<LL, vector<LL>, greater<>> LSH; // LL small heap
typedef priority_queue<int, vector<int>, greater<>> ISH; // int small heap
const int P = 131; // 131 353 13331
const double EXP = 1e-9;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const LL LNF = 0x3f3f3f3f3f3f3f3f;
const int N = 300010, M = 2 * N;
void IOS() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
int n;
ISH q;
void solve() {
cin >> n;
LL res = 0;
for (int i = 1; i <= n; i ++ ) {
int x;
cin >> x;
q.push(x);
if (q.top() < x) {
res += x - q.top();
q.pop();
q.push(x);
}
}
cout << res << endl;
}
signed main() {
IOS();
int t = 1;
// cin >> t;
while (t -- ) {
solve();
}
return 0;
}