1. 程式人生 > >1153 Keep the Customer Satisfied 顧客是上帝(優先佇列貪心)

1153 Keep the Customer Satisfied 顧客是上帝(優先佇列貪心)

大體題意:

給你n (n <= 80w)個工作,告訴你每個工作的持續時間和終止日期,問最多能完成多少個工作?

思路:

其實思路,在PDF中已經很明顯了,先按照終止日期排序,因為要想完成更多的任務,你就必須先完成終止日期小的任務。

其次就是選任務了,在PDF文章中,他選擇了2,3,5,6任務,1沒有選擇,但1一開始肯定是符合要求的,所以思路肯定是排完序後,先選擇,當選擇不了(時間不允許時),看看當前選擇不了的任務是否比已選擇的任務中最差的更加優,所以就把更優的選入,最差的扔掉。

所以很明顯這裡用到了優先佇列,很明顯當一個任務選擇不了時,那麼你這個任務的終止日期肯定不小於你已經選擇的任務的終止日期(因為已經排序了嘛),那麼看最優還是最差就看持續時間了,當然是持續時間越少越好啦,所以發現當前任務的持續時間比已經選擇任務的最長時間短的話,那麼就符合比最差解更優,所以扔掉已經選擇的任務,加入當前任務,最後輸出優先佇列中元素個數就是答案啦!

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
const int maxn = 800000 + 10;
struct Node{
    int s,t,id;
    bool operator < (const Node & rhs) const {
        return s < rhs.s;
    }
}p[maxn];
priority_queue<Node>q;
bool cmp(const Node &lhs,const Node & rhs){
    return lhs.t < rhs.t || (lhs.t == rhs.t && lhs.s < rhs.s);
}
int solve(int n){
    while(!q.empty())q.pop();
    int ans = 0,cur = 0;
    for (int i = 0; i < n; ++i){
        if (cur + p[i].s <= p[i].t){
            q.push(p[i]);
            cur += p[i].s;
        }else {
            if (q.empty())continue;
            Node u = q.top();
            if (u.s > p[i].s){
                cur = cur - u.s + p[i].s;
                q.pop();
                q.push(p[i]);
            }
        }

    }
//    while(!q.empty()){
//        printf("%d ",q.top().id);
//        q.pop();
//    }
    return q.size();
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        int n;
        scanf("%d",&n);
        for (int i = 0; i < n ; ++i){
            scanf("%d%d",&p[i].s,&p[i].t);
        }
        sort(p,p+n,cmp);
        for (int i = 0; i < n; ++i)p[i].id = i+1;
        printf("%d\n",solve(n));
        if (T)puts("");
    }

    return 0;
}

/*
1
6
7 15
8 20
6 8
4 9
3 21
5 22
*/