Description
小刚在玩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
题解:
贪心!
先按截稿时间/花费时间从小到大来排一遍序, 因为截稿时间靠前的肯定要先选,截稿时间相同的肯定要选时间短的。
然后我们建个堆,堆顶是花费时间最大的元素。
① 然后从第一个开始,若当前任务所需时间+之前的总时间小于等于
当前截稿时间,则扔进堆里, ans++。 //能够完成,更新 tot
若大于,这时要从它前面所有任务中选一个花费时间最长的(就是堆
顶元素, 记为 y)和它比较,
②若当前任务所需时间 > y,则不扔进堆中。 //若替换,当前任务仍
然不能完成;
③若当前任务所需时间 < y,则把 y 替换成当前任务。 //当前任务能
够完成, ans 数不变,使得 now 减小,更加优;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long LL;
priority_queue <LL> q;
struct qer
{
LL cost, ed;
}jz[233333];
bool cmp(qer a, qer b)
{
if (a.ed == b.ed)
return a.cost < b.cost;
return a.ed < b.ed;
}
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
scanf("%lld%lld", &jz[i].cost, &jz[i].ed);
sort(jz+1, jz+n+1, cmp);
LL now = 0;
LL ans = 0;
for (int i = 1; i <= n; i++)
{
if (now + jz[i].cost <= jz[i].ed)
q.push(jz[i].cost), now += jz[i].cost, ans++;
else if (now + jz[i].cost > jz[i].ed)
{
if (!q.empty() && q.top() > jz[i].cost)
{
now = now - q.top() + jz[i].cost;
q.pop();
q.push(jz[i].cost);
}
}
}
cout << ans;
return 0;
}