跳到正文

个人记录

20260726 - 反悔贪心总结

kumi125约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年7月27日
更新
2026年7月27日
篇幅
约 5 分钟

版本

  1. v1当前

反悔贪心的原则就是:

1.能选就选。

2.不能选就通过撤回之前的某个操作使得能选择当前。

HUR-Warehouse Store

我们先思考直接贪心是否可行:每次累计 aia_i,只要大于等于 bib_i,就增加一个购买人数,但很容易造出反例,比如:

代码
5
4 0 0 0 0
4 1 1 1 1

按照之前的贪心原则,只会选择第一个顾客,但实际上选择后四个才是最优的。

对于每天,先统计当前进货完的商品个数,如果能买当前的就买,不能就需要看能不能通过撤销某一次购买来获得当前的,此时一定是要撤回 一个花费商品数 最多的,这也很好理解,因为如果撤销两个或以上,个数就会少 11,肯定用最大的最优。

C++
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;
const ll N = 3e5 + 5;
const ll M = 1e5 + 5;
const ll INF = 1e18;
const ll MOD = 1e9 + 7;
struct node{
	ll x,id;
	bool operator < (const node &d) const{
		return x < d.x; //大跟堆
	}
};
ll n,a[N],b[N];
bool vis[N]; //表示某一个是否选择
priority_queue<node> q;
void work(){
	cin >> n;
	for(int i = 1;i <= n;i++){
		cin >> a[i];
	}
	for(int i = 1;i <= n;i++){
		cin >> b[i];
	}
	ll sum = 0;
	for(ll i = 1;i <= n;i++){
		sum += a[i]; //计算
		if(sum >= b[i]){ //能满足顾客
			sum -= b[i]; //满足
			q.push((node){b[i],i}); //放入
		}else if(!q.empty() && b[i] < q.top().x){ //如果堆顶的最大值能满足当前的需求。
			sum += (q.top().x - b[i]); //加上之前所花费的再扣除当前花费
			q.pop();
			q.push((node){b[i],i}); //放入
		}
	}
	cout << q.size() << "\n"; //个数
	while(!q.empty()){
		vis[q.top().id] = 1; //标记一下选择的位置
		q.pop();
	}
	for(int i = 1;i <= n;i++){
		if(vis[i]){
			cout << i << " "; //输出
		}
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);cout.tie(nullptr);
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	int oT_To = 1;
	//cin >> oT_To;
	while(oT_To--){ work();}
	return 0;
}

建筑抢修

与上题类似,我们把建筑的时间放入小跟堆,接着能修补就修吗,不能就取堆顶元素补当前的。

C++
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;
const ll N = 2e5 + 5;
const ll M = 1e5 + 5;
const ll INF = 1e18;
const ll MOD = 1e9 + 7;
struct node{
	ll t1,t2;
}a[N];
ll n,sum,ans;
priority_queue<ll> q;
bool cmp(node x,node y){
	return x.t2 < y.t2;
}
void work(){
	cin >> n;
	for(int i = 1;i <= n;i++){
		cin >> a[i].t1 >> a[i].t2;
	}
	sort(a + 1,a + 1 + n,cmp);
	for(int i = 1;i <= n;i++){
		sum += a[i].t1;
		q.push(a[i].t1);
		if(sum <= a[i].t2){
			ans++;
		}else{
			sum -= q.top();
			q.pop();
		}
	}
	cout << ans;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);cout.tie(nullptr);
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	int oT_To = 1;
	//cin >> oT_To;
	while(oT_To--){ work();}
	return 0;
}
原文