跳到正文

题解

题解:UVA1153 顾客是上帝 Keep the Customer Satisfied

Fire_flys约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年6月4日
篇幅
约 2 分钟
题目
UVA1153

版本

  1. v1当前

这道题其实十分简单,就是一个反悔贪心。

首先很显然的一个想法就是按照任务的完成时间排序。细想一下,完成时间早的我们肯定先做会比晚做更好,但是单单这样贪心肯定是不行的。比如一个完成时间早但是要完成这个任务却要很久,这其中的时间够我们做很多任务了。这时候因为完成任务的先后顺序是不计的,所以我们可以反悔一下,把完成任务时间多的给扔掉。

具体怎么实现呢?我们可以用一个变量维护当前时间,若当前时间加上完成任务所需时间比必须完成任务的时间早,那我们就把这个任务加入一个优先队列,表示已经做了。否则我们把优先队列中完成所需时间最大的任务给拿出来与当前的比较,如果当前的更小就把已经做了的给扔掉转头去做这个。更小的肯定更优嘛。

还有不懂的可以看代码。

C++
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=8e5+10;
struct node{
	int l,r,tot;
}a[N];
int ans=0;
bool cmp(node &x,node &y){
	return x.r<y.r;
}
bool operator < (const node &x,const node &y){
	return x.tot<y.tot;
}
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	int T;cin>>T;
	while(T--){
		int n;cin>>n;ans=0;
		priority_queue<node> q;
		while(q.size())q.pop();
		for(int i=1;i<=n;i++){
			cin>>a[i].tot>>a[i].r;
			a[i].l=a[i].r-a[i].tot;
		}
		sort(a+1,a+1+n,cmp);
		for(int i=1;i<=n;i++){
			if(ans+a[i].tot<=a[i].r){
				ans+=a[i].tot;
				q.push(a[i]);
			}
			else if(q.size()){
				node t=q.top();
				if(a[i].tot<t.tot){
					q.pop();
					q.push(a[i]);
					ans-=t.tot;
					ans+=a[i].tot;
				}
			}
		}
		cout<<q.size()<<"\n";
		if(T)cout<<'\n';
	}
	return 0;
}
原文
存档评论1 条抓取于