約翰有太多的工做要作。爲了讓農場高效運轉,他必須靠他的工做賺錢,每項工做花一個單位時間。 他的工做日從0時刻開始,有10^9個單位時間。在任一時刻,他均可以選擇編號1~N的N(1 <= N <= 10^6)項工做中的任意一項工做來完成。 由於他在每一個單位時間裏只能作一個工做,而每項工做又有一個截止日期,因此他很難有時間完成全部N個工做,雖然仍是有可能。 對於第i個工做,有一個截止時間D_i(1 <= D_i <= 10^9),若是他能夠完成這個工做,那麼他能夠獲利P_i( 1<=P_i<=10^9 ). 在給定的工做利潤和截止時間下,約翰可以得到的利潤最大爲多少.c++
Farmer John has so very many jobs to do! In order to run the farm efficiently, he must make money on the jobs he does, each one of which takes just one time unit.spa
His work day starts at time 0 and has 1,000,000,000 time units (!). He currently can choose from any of N (1 <= N <= 100,000) jobs翻譯
conveniently numbered 1..N for work to do. It is possible butcode
extremely unlikely that he has time for all N jobs since he can only work on one job during any time unit and the deadlines tend to fall so that he can not perform all the tasks.orm
Job i has deadline D_i (1 <= D_i <= 1,000,000,000). If he finishes job i by then, he makes a profit of P_i (1 <= P_i <= 1,000,000,000).排序
What is the maximum total profit that FJ can earn from a given list of jobs and deadlines? The answer might not fit into a 32-bit integer.ci
輸入格式:rem
Line 1: A single integer: Nget
Lines 2..N+1: Line i+1 contains two space-separated integers: D_i and P_iit
輸出格式:
輸入樣例#1:
3
2 10
1 5
1 7
輸出樣例#1:
17
Complete job 3 (1,7) at time 1 and complete job 1 (2,10) at time 2 to maximize the earnings (7 + 10 -> 17).
很容易想到按時間從小到大排序,由於它的截止時間越長,咱們就能夠了把前面的時間去留給其餘物品,而後貪心的去選,可是這樣會WA,爲何?
看一下這種狀況,咱們在前面選了價值較小的工做,可是當前有一個價值比它大得多的工做咱們卻無法選,這個時候就會後悔,因此這是一道能夠反悔的貪心題
那麼怎麼反悔呢?咱們用一個小根堆去維護,每次選的工做,咱們把它的價值丟進小根堆,若是碰到一個選不了的工做,咱們就拿它和堆頂比較,若是比它大,那麼堆頂其實不必選的,因此把它彈出去
具體狀況是什麼樣子的呢?(如下咱們用\(t\)表示工做的截止時間)
由於一個單位時間只能作一個工做,因此堆的元素個數表示至少已通過了\(size\)個單位時間
1. 當前工做的t小於堆的元素個數,說明當前工做已經截止了,不用管 2. 當前工做的t大於堆內元素個數,直接插入 3. 當前工做的t等於堆內元素個數,與堆頂比較,看誰更優
#include<bits/stdc++.h> #define in(i) (i=read()) #define il extern inline #define rg register #define Min(a,b) ((a)<(b)?(a):(b)) #define Max(a,b) ((a)>(b)?(a):(b)) #define lol long long using namespace std; const lol N=1e6+10; lol read() { lol ans=0, f=1; char i=getchar(); while (i<'0' || i>'9') {if(i=='-') f=-1; i=getchar();} while (i>='0' && i<='9') ans=(ans<<1)+(ans<<3)+(i^48), i=getchar(); return ans*f; } struct Node { lol day,v; bool operator < (const Node &a) const {return day<a.day;} }t[N]; priority_queue<lol,vector<lol>,greater<lol> >q; int main() { lol n,ans=0; in(n); for (lol i=1;i<=n;i++) in(t[i].day), in(t[i].v); sort(t+1,t+1+n); for (lol i=1;i<=n;i++) { if(t[i].day<q.size()) continue; else if(t[i].day==q.size()) { if(t[i].v>q.top()) { ans-=q.top(); q.pop(); q.push(t[i].v); ans+=t[i].v; } }else ans+=t[i].v,q.push(t[i].v); }cout<<ans<<endl; }