码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-07-04 15:33:06      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

题意:给定 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;
}

 

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

标签:

原文地址:http://www.cnblogs.com/dwtfukgv/p/5640305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!