洛谷P4053 建筑抢修(贪心加优先队列)

题目链接

https://www.luogu.org/problemnew/show/P4053

题解:定义一个结构体,把修楼需要的时间和楼还有多长时间损坏存进去。以损坏时间先后排一下序,优先修快坏的,然后存一个已用时间,再建立一个堆来维护已修的楼用时最大的。如果判断下个楼没时间修了,就把修它需要的时间和已经修的楼中最大的时间比一下谁少。如果当前楼比之前的楼消耗的时间小,那就不修之前最大的楼,改修这个。虽然不会多修楼,但是可以省下更多时间给后面的楼。

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<math.h>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
using namespace std;
typedef long long LL;
struct MyStruct
{
	int spe;
	int end;
}build[150005];
priority_queue<int>Q;
int n, t;

int cmp(MyStruct a,MyStruct b){
	return a.end < b.end;
}

int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> build[i].spe >> build[i].end;
	}
	t = 0;
	int ans = 0;
	sort(build, build + n, cmp);
	for (int i = 0; i < n; i++) {
		if (t + build[i].spe <= build[i].end) {
			Q.push(build[i].spe);
			t += build[i].spe;
			ans++;
		}
		else {
			if (!Q.empty() && build[i].spe < Q.top()) {
				t -= Q.top(); Q.pop();
				t += build[i].spe;
				Q.push(build[i].spe);
			}
		}
	}
	cout << ans;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值