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


    题意:给定 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
    ", solve());
            if(T)  printf("
    ");
        }
        return 0;
    }
    
  • 相关阅读:
    第一个爬虫和测试
    数学规律
    自定义手绘
    tqqqy的成绩表
    Linux常用命令-netstat
    文档查看命令 cat more less tail head
    Linux三剑客-常用命令
    IO多路复用模型
    redis 的线程模型
    为什么需要缓存?
  • 原文地址:https://www.cnblogs.com/dwtfukgv/p/5640305.html
Copyright © 2020-2023  润新知