大体题意:
给你n (n <= 80w)个工作,告诉你每个工作的持续时间和终止日期,问最多能完成多少个工作?
思路:
其实思路,在PDF中已经很明显了,先按照终止日期排序,因为要想完成更多的任务,你就必须先完成终止日期小的任务。
其次就是选任务了,在PDF文章中,他选择了2,3,5,6任务,1没有选择,但1一开始肯定是符合要求的,所以思路肯定是排完序后,先选择,当选择不了(时间不允许时),看看当前选择不了的任务是否比已选择的任务中最差的更加优,所以就把更优的选入,最差的扔掉。
所以很明显这里用到了优先队列,很明显当一个任务选择不了时,那么你这个任务的终止日期肯定不小于你已经选择的任务的终止日期(因为已经排序了嘛),那么看最优还是最差就看持续时间了,当然是持续时间越少越好啦,所以发现当前任务的持续时间比已经选择任务的最长时间短的话,那么就符合比最差解更优,所以扔掉已经选择的任务,加入当前任务,最后输出优先队列中元素个数就是答案啦!
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
const int maxn = 800000 + 10;
struct Node{
int s,t,id;
bool operator < (const Node & rhs) const {
return s < rhs.s;
}
}p[maxn];
priority_queue<Node>q;
bool cmp(const Node &lhs,const Node & rhs){
return lhs.t < rhs.t || (lhs.t == rhs.t && lhs.s < rhs.s);
}
int solve(int n){
while(!q.empty())q.pop();
int ans = 0,cur = 0;
for (int i = 0; i < n; ++i){
if (cur + p[i].s <= p[i].t){
q.push(p[i]);
cur += p[i].s;
}else {
if (q.empty())continue;
Node u = q.top();
if (u.s > p[i].s){
cur = cur - u.s + p[i].s;
q.pop();
q.push(p[i]);
}
}
}
// while(!q.empty()){
// printf("%d ",q.top().id);
// q.pop();
// }
return q.size();
}
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
for (int i = 0; i < n ; ++i){
scanf("%d%d",&p[i].s,&p[i].t);
}
sort(p,p+n,cmp);
for (int i = 0; i < n; ++i)p[i].id = i+1;
printf("%d\n",solve(n));
if (T)puts("");
}
return 0;
}
/*
1
6
7 15
8 20
6 8
4 9
3 21
5 22
*/