1029: [JSOI2007]建筑抢修
Time Limit: 4 Sec Memory Limit: 162 MBDescription
小刚在玩JSOI提供的一个称之为“建筑抢修”的电脑游戏:经过了一场激烈的战斗,T部落消灭了所有z部落的
入侵者。但是T部落的基地里已经有N个建筑设施受到了严重的损伤,如果不尽快修复的话,这些建筑设施将会完全
毁坏。现在的情况是:T部落基地里只有一个修理工人,虽然他能瞬间到达任何一个建筑,但是修复每个建筑都需
要一定的时间。同时,修理工人修理完一个建筑才能修理下一个建筑,不能同时修理多个建筑。如果某个建筑在一
段时间之内没有完全修理完毕,这个建筑就报废了。你的任务是帮小刚合理的制订一个修理顺序,以抢修尽可能多
的建筑。
Input
第一行是一个整数N接下来N行每行两个整数T1,T2描述一个建筑:修理这个建筑需要T1秒,如果在T2秒之内还
没有修理完成,这个建筑就报废了。
Output
输出一个整数S,表示最多可以抢修S个建筑.N < 150,000; T1 < T2 < maxlongint
Sample Input
4
100 200
200 1300
1000 1250
2000 3200
100 200
200 1300
1000 1250
2000 3200
Sample Output
3
从感性来看,如果想要修尽可能多的塔,一定要把限期靠前的先造
因此我们先按照限期从小到大排序
然后在考虑贪心
我们存一个造完之前所有塔的结束时间,当新加入一个塔时,如果依旧没要超过这个塔的对应时间,就直接把他加入到我们的修建序列里
如果发现现有时间造不完这个塔,我们就拿大根堆堆顶的塔和他交换(如果比他大)
这样我们总的建造时间会减小,但总数不变
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 #define LL long long 7 ?8 using namespace std; 9 10 const int MAXN = 2e5 + 10; 11 int N;12 int ans = 0;13 int cnt = 0;14 priority_queue<int> q;15 struct building {16 ????int t1;17 ????int t2;18 } b[MAXN];19 20 inline LL read()21 {22 ????LL x = 0, w = 1; char ch = 0;23 ????while(ch < ‘0‘ || ch > ‘9‘) {24 ????????if(ch == ‘-‘) {25 ????????????w = -1;26 ????????}27 ????????ch = getchar();28 ????}29 ????while(ch >= ‘0‘ && ch <= ‘9‘) {30 ????????x = x * 10 + ch - ‘0‘;31 ????????ch = getchar();32 ????}33 ????return x * w;34 }35 36 bool cmp(building a, building b)37 {38 ????if(a.t2 == b.t2) {39 ????????return a.t1 < b.t1;40 ????}41 ????return a.t2 < b.t2;42 }43 int main()44 {45 ????N = read();46 ????for(int i = 1; i <= N; i++) {47 ????????b[i].t1 = read(), b[i].t2 = read();48 ????}49 ????sort(b + 1, b + N + 1, cmp);50 ????for(int i = 1; i <= N; i++) {51 ????????if(cnt + b[i].t1 <= b[i].t2) {52 ????????????q.push(b[i].t1);53 ????????????cnt += b[i].t1;54 ????????????ans++;55 ????????} else {56 ????????????if(!q.empty()) {57 ????????????????int t = q.top();58 ????????????????if(b[i].t1 < q.top()) {59 ????????????????????cnt = cnt - t + b[i].t1;60 ????????????????????q.pop();61 ????????????????????q.push(b[i].t1);62 ????????????????}63 ????????????}64 ????????}65 ????}66 ????printf("%d\n", ans);67 }
bzoj 1029 [JSOI2007]建筑抢修 - 贪心 + 大根堆
原文地址:https://www.cnblogs.com/wuenze/p/8448827.html