题目:
约翰有太多的工作要做。为了让农场高效运转,他必须靠他的工作赚钱,每项工作花一个单位时间。
他的工作日从0时刻开始,有109 个单位时间。在任一时刻,他都可以选择编号1~N的N(1 <= N <= 106)项工作中的任意一项工作来完成。
因为他在每个单位时间里只能做一个工作,而每项工作又有一个截止日期,所以他很难有时间完成所有N个工作,虽然还是有可能。 对于第i个工作,有一个截止时间D_i(1 <= D_i <= 10^9),
如果他可以完成这个工作,那么他可以获利P_i( 1<=P_i<=10^9 ). 在给定的工作利润和截止时间下,约翰能够获得的利润最大为多少.
输入格式
-
Line 1: A single integer: N
-
Lines 2…N+1: Line i+1 contains two space-separated integers: D_i and P_i
输出格式
- Line 1: A single number on a line by itself that is the maximum possible profit FJ can earn.
思路看图解:
/* 算法实现
3
2 10
1 5
1 7
排序:
1 5
1 7
2 10
| |
| |
| |
| |
1 |__5__|
| |
| |
| |
| |
1 |_7___|<<--因为在结束时间相同之前,取7划算,取出5放入7
| |
| |
| |
2 | 10 |2比1大所以放入顶部
1 |__5__|
*/
//使用优先队列
#include<bits/stdc++.h>
using namespace std;
#include<queue>
#include<vector>
priority_queue<int,vector<int>,greater<int> > a;//从小到大,头部小
struct asd{
int di,pi;
}b[100005];
bool comp(struct asd x,struct asd y){
return x.di<y.di;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>b[i].di>>b[i].pi;
}
sort(b,b+n,comp);
long long ans=0;
for(int i=0;i<n;i++){
if(b[i].di<=a.size()){//表示第i个时间和之前冲突 ,因为同一时间只能存在一个,所以元素个数可以代替存在的时间最大值
if(b[i].pi>a.top()){//在上一基础上,i的pi大于a顶部的,交换
ans-=a.top();
ans+=b[i].pi;
a.pop();
a.push(b[i].pi);
}
}else{//如果时间不冲突,直接放入
ans+=b[i].pi;
a.push(b[i].pi);
}
}
cout<<ans<<endl;
return 0;
}
来源:https://blog.csdn.net/qq_44009311/article/details/99474675