1. 程式人生 > >Uva 1153 Keep the Customer Satisfied (貪心+優先隊列)

Uva 1153 Keep the Customer Satisfied (貪心+優先隊列)

最長 題意 code log algo cmp cst name node

題意:已知有n個工作,已知每個工作需要的工作時間qi和截至時間di,工作只能串行完成,問最多能完成多少個工作

思路:首先我們按照截至時間從小到大排序,讓它們依次進入優先隊列中,當發生執行完成時間大於截至時間時,我通過優先隊列把工作中最長的需要時間出隊

優先隊列的比較函數:

struct cp
{
    bool operator () (node a,node b)
    {
        //可以理解為我如何讓後入隊的優先出隊
        if(b.need>a.need) return true;
        else return false;
    }
};

代碼:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>

using namespace std;
const int maxn=800005;
struct node
{
    int need,ed;
}data[maxn];

struct cp
{
    bool operator () (node a,node b)
    {
        if(b.need>a.need) return
true; else return false; } }; bool cmp(node a,node b) { if(a.ed<b.ed) return true; else if(a.ed==b.ed) { if(a.need<b.need) return true; else return false; } else return false; } int main() { int n; int t; cin>>t; while(t--) { cin
>>n; for(int i=0;i<n;i++) { cin>>data[i].need>>data[i].ed; } sort(data,data+n,cmp); priority_queue<node,vector<node>,cp> q; int tmp=0,ans=0; for(int i=0;i<n;i++) { q.push(data[i]); tmp=tmp+data[i].need; if(tmp>data[i].ed) { node k=q.top(); q.pop(); tmp=tmp-k.need; ans--; } ans++; } if(ans<=0) ans=0; cout<<ans<<endl; if(t) cout<<endl; } return 0; }

Uva 1153 Keep the Customer Satisfied (貪心+優先隊列)