题意:给定n个工作的需要时间和截止时间,工作只能线性来完成,问最多能完成多少个工作。
题解:容易想到,先将工作根据截止时间排序,截止时间较早者靠前,之后维护一个时间变量cnt和优先队列,若当前工作cnt+q<=d则将q放入优先队列,否则将当前q与priority_queue.top比较,若q小则将top pop掉并push q,并cnt-=queue.top+q从而减少当前所耗时间,从而实现贪心,最后输出priority_queue.size即可。
注意:需要判断!queue.empty,否则会re。
附上AC代码
#include <bits/stdc++.h>
#define FOPI freopen("INPUT.TXT", "r", stdin)
#define DOPI freopen("OUTPUT.TXT", "w", stdout)
#define FOR(i, x, y) for(int i = x; i <= y; i ++)
#define ROF(i, x, y) for(int i = x; i >= y; i --)
using namespace std;
typedef long long int ll;
const int ind=0x3f3f3f3f,N=1e6+10;
const ll inlld=0x3f3f3f3f3f3f3f3f,mod=998244353;
struct node
{
int x,y;
}s[N];
bool cmp(node a,node b)
{
if(a.y==b.y) a.x<b.x;
return a.y<b.y;
}
int main()
{
// DOPI;
ios::sync_with_stdio(false);
int t,n;cin>>t;
int fg=0;
while(t--){
cin>>n;
if(!fg)fg=1;
else cout << endl;
for(int i=1;i<=n;i++)cin>>s[i].x>>s[i].y;
sort(s+1,s+1+n,cmp);
priority_queue<int> q;
int cnt=0;
for(int i=1;i<=n;i++){
if(cnt+s[i].x<=s[i].y){
q.push(s[i].x);
cnt+=s[i].x;
}
else if(!q.empty()){
if(q.top()>s[i].x){
cnt=cnt-q.top()+s[i].x;
q.pop();q.push(s[i].x);
}
}
}cout << q.size() << endl;
}
return 0;
}
/*
1
6
7 15
8 20
6 8
4 9
3 21
5 22
*/
来源:CSDN
作者:愿你一生努力,一生被爱
链接:https://blog.csdn.net/weixin_43589675/article/details/104011098