贪心算法拓展(反悔贪心)

相信大家对贪心算法已经见怪不怪了,但是一旦我们的决策条件会随着我们的步骤变化,我们该怎么办呢?有没有什么方法可以反悔呢?

今天就来讲可以后悔的贪心算法,反悔贪心。

https://www.luogu.com.cn/problem/CF865Dhttps://www.luogu.com.cn/problem/CF865D

题目描述

You can perfectly predict the price of a certain stock for the next 𝑁 days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the 𝑁 days you would like to again own zero shares, but want to have as much money as possible.

输入格式

Input begins with an integer 𝑁N (2<=𝑁<=3⋅105), the number of days.

Following this is a line with exactly 𝑁N integers 𝑝1,𝑝2,...,𝑝𝑁(1<=𝑝𝑖<=106) . The price of one share of stock on the 𝑖 -th day is given by 𝑝𝑖​ .

输出格式

Print the maximum amount of money you can end up with at the end of 𝑁 days.

输入输出样例

输入 #1

复制代码
9
10 5 4 7 9 12 6 2 10

输出 #1

复制代码
20

输入 #2

复制代码
20
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4

输出 #2

复制代码
41

就像买卖股票,谁都不知道接下来股票的趋势,但如果我们知道了趋势,又如何让自己的收益最大化呢?

因此,我们可以先考虑两种情况:

一:当第一天的价格高于第二天时,我们就只要屯着,因为卖出去是没有收益的。

二:反之,我们每次遇见第二天的价格高于第一天时,我们就直接先考虑卖出(能赚一点是一点),我们会获得收益,那假如之后价格更高怎么办?当然是反悔了,我们用一个小根堆来存储已经路过的天数,秉承着只要有钱赚就卖的原则,我们充分利用priority_queue的强大优势,当堆顶元素比当日价格低的时候,我们就卖掉(映射到代码就是pop()),然后将总获利加上差价,就是买股票的钱,那么怎么反悔呢,我们在pop堆顶元素的时候,将一个当日的股价压入堆,无论在哪里,只要堆不空,那么只要有股价高于堆顶元素的就重复以上步骤,这样做不会舍弃更高的利润,而是将难以维护的决策变成了类似滚雪球一样的方式,这就是反悔贪心的核心操作。比较抽象,需要仔细理解体会。

最后附上完整代码:

复制代码
#include <bits/stdc++.h>

using namespace std;

typedef long long LL;
const int N = 1e6 + 10;

int p[N]; 
priority_queue<int, vector<int>, greater<int> > q;
int n;
LL ans = 0;

int main()
{
	cin >> n;
	
	for(int i = 1; i <= n; i ++)
		cin >> p[i];
		
	for(int i = 1; i <= n; i ++)
	{
		if(!q.empty() && p[i] > q.top())
		{
			ans += p[i] - q.top();
			q.pop();
			q.push(p[i]);
		}
		q.push(p[i]);
	}
	
	cout << ans << endl;
}

tip:这是一次CF上的题,在洛谷上提交的时候要记得绑定CF账号哦>_<!!!

相关推荐
野渡拾光1 小时前
【考研408数据结构-05】 串与KMP算法:模式匹配的艺术
数据结构·考研·算法
tainshuai3 小时前
用 KNN 算法解锁分类的奥秘:从电影类型到鸢尾花开
算法·分类·数据挖掘
Coovally AI模型快速验证9 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·yolo·计算机视觉·transformer·无人机
pusue_the_sun9 小时前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
RaymondZhao3410 小时前
【全面推导】策略梯度算法:公式、偏差方差与进化
人工智能·深度学习·算法·机器学习·chatgpt
zhangfeng113310 小时前
DBSCAN算法详解和参数优化,基于密度的空间聚类算法,特别擅长处理不规则形状的聚类和噪声数据
算法·机器学习·聚类
啊阿狸不会拉杆11 小时前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
小学生的信奥之路11 小时前
洛谷P3817题解:贪心算法解决糖果分配问题
c++·算法·贪心算法
你知道网上冲浪吗12 小时前
【原创理论】Stochastic Coupled Dyadic System (SCDS):一个用于两性关系动力学建模的随机耦合系统框架
python·算法·数学建模·数值分析
地平线开发者13 小时前
征程 6 | PTQ 精度调优辅助代码,总有你用得上的
算法·自动驾驶