题意:已知有n个工作,已知每个工作需要的工作时间qi和截至时间di,工作只能串行完成,问最多能完成多少个工作
分析:贪心,先按截止时间排序,建优先级队列,主要是要取出截止时间大,需要时间大的工作,每次加入队列时要进行比较,比队列中截止时间最长的队列的需要时间少,并且能在规定时间做完,则加入队列,因为刚加入的截止时间又大,需要时间又小,比起队列中最大的,肯定是刚加入的更好了。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
const int maxn = 8e5 + 5;
struct node {
int q, d;
bool operator < (const node &p) const {//优先队列最大值优先
return q < p.q;
}
};
node a[maxn];
int n;
bool cmp(const node &p, const node &qq) {//排序,按截止时间
return p.d < qq.d || (p.d == qq.d && p.q < qq.q);
}
int main() {
// freopen("in.txt", "r", stdin);
int T; cin >> T;
while (T--) {
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d %d", &a[i].q, &a[i].d);
sort(a, a + n, cmp);//排序
priority_queue<node> pq;
int s = 0;
for (int i = 0; i < n; ++i) if (a[i].q <= a[i].d)//注意工作本身就有问题的
if (pq.empty()) { pq.push(a[i]); s = a[i].q; }
else if (s + a[i].q <= a[i].d) { s += a[i].q; pq.push(a[i]); }//能在截止时间前完成
else {
node u = pq.top(); pq.pop();
if (u.q > a[i].q && s - u.q + a[i].q <= a[i].d) { pq.push(a[i]); s -=( u.q - a[i].q); }//q 比队列的最长的小
else pq.push(u);
}
printf("%d\n", pq.size());
if (T) printf("\n");
}
return 0;
}