您的位置:首页 > 其它

UVa 1153 Keep the Customer Satisfied (贪心+优先队列)

2016-07-04 14:10 309 查看
题意:给定 n 个工作,已知每个工作要用的时间 q 和 截止时间 d,问你最多完成多少个工作,每次最多能运行一个工作。

析:这个题是贪心,应该能看出来,关键是贪心策略是什么,这样想,先按截止时间排序,那么这样,所有的工作就是都是按照截止时间排,因为我们先保证,

截止时间早的先选,然后再从把所有的遍历一下,利用优先队列,q大的优先,然后考虑,后面的,如果后面的还能在截止时间内完成,就放入,如果不能,那么,

和队列中q最长的比,如果比队列中q最长的还长,那么就不要了,否则,那么就删除最长的,把它放进去,想想为什么,因为,如果是这样,那么工作数量不减少,

但是能够剩下更多的时间去完成其他的。如果不懂优先队列点击 http://www.cnblogs.com/dwtfukgv/articles/5640285.html

注意的是,有一个坑,我被坑了好几天。。。。那就是那个 q可能比 d 还大,这样的是不能考虑的。。。。。

代码如下:

#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 solve(){
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);
}

return pq.size();
}

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);//排序

printf("%d\n", solve());
if(T)  printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: