跳到正文

算法·理论

反悔贪心

afo_ing约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月7日
篇幅
约 4 分钟

版本

  1. v1当前

反悔贪心详解

1. 什么是反悔贪心?

普通贪心:每一步选当前最好的,不回头。

反悔贪心:允许“后悔”,如果后面发现更好的,就撤销之前的选择。

2.反悔贪心的两种实现

方法1:反悔堆(优先队列)

适用问题:需要动态替换较差选择的场景(如任务调度)。

核心代码:

C++
priority_queue<int, vector<int>, greater<int>> pq; // 小根堆
for (任务 in 所有任务) {
    if (能直接选) {
        pq.push(任务收益);
        总收益 += 任务收益;
    }
    else if (任务收益 > pq.top()) { // 反悔
        总收益 -= pq.top();
        pq.pop();
        pq.push(任务收益);
        总收益 += 任务收益;
    }
}

P2949 [USACO09OPEN] Work Scheduling G(反悔堆模版题目)

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
bool cmp(const pair<int,int>&a,const pair<int,int>&b){
	return a.first<b.first;//按照截止时间排序
}
int n;//项目个数
signed main(){
	scanf("%lld",&n);
	vector<pair<int,int>>num;//first:截止时间,second:收益
	for(int i=1;i<=n;i++){
		int x,y;
		scanf("%lld%lld",&x,&y);
		num.push_back({x,y});
	}
	sort(num.begin(),num.end(),cmp);
	priority_queue<int,vector<int>,greater<int>>dq;//小根堆
	int sum=0;
	for(const auto&[time,money]:num){
		//正常贪心,直接插入
		if(dq.size()<time){
			dq.push(money);
			sum+=money;
		}
		//反悔替换
		else if(!dq.empty()&&money>dq.top()){
			sum-=dq.top();
			dq.pop();
			dq.push(money);
			sum+=money;
		}
	}
	printf("%lld",sum);
	return 0;
}

代码先将工作按截止时间从小到大排序,确保优先处理时间紧迫的任务。

使用小根堆(优先队列)维护已选任务的收益,堆顶始终是当前收益最小的任务。

遍历每个任务时,若已选任务数(dq.size())小于截止时间,说明截止前有空闲时间,直接加入堆并累加收益;

若已无空闲时间,但当前任务收益高于堆顶,说明可用高收益任务替换低收益任务(反悔操作),通过移除堆顶并加入当前收益,更新总收益。

方法2:反悔自动机(差值反悔)

适用问题:允许“先选再反悔”的场景(如股票买卖)。

核心代码:

C++
int cost = prices[0]; // 初始买入成本
for (int i = 1; i < prices.size(); i++) {
    if (prices[i] < cost) {
        cost = prices[i]; // 遇到更低价,更新成本
    }
    else if (prices[i] > cost + fee) {
        利润 += prices[i] - cost - fee;
        cost = prices[i] - fee; // 反悔:允许后续更高价
    }
}
原文